import { NextRequest, NextResponse } from "next/server";

const OS_BASE = "https://api.onesignal.com";

/**
 * Resolves a OneSignal user-2 identity conflict:
 *   external_id is already claimed by a different onesignal_id.
 *
 * Steps:
 *   1. Fetch the user that currently owns the external_id.
 *   2. Delete that user so the alias is freed.
 *   3. The client can then retry OneSignal.login(externalId) successfully.
 */
export async function POST(req: NextRequest) {
  try {
    const { appId, restKey, externalId } = await req.json() as {
      appId?: string;
      restKey?: string;
      externalId?: string;
    };

    if (!appId || !restKey || !externalId) {
      return NextResponse.json(
        { error: "appId, restKey, and externalId are required" },
        { status: 400 },
      );
    }

    const headers = {
      Authorization: `Key ${restKey}`,
      "Content-Type": "application/json",
      Accept: "application/vnd.onesignal.v1+json",
    };

    // 1. Verify the conflicting user actually exists under this external_id
    const getRes = await fetch(
      `${OS_BASE}/apps/${appId}/users/by/external_id/${encodeURIComponent(externalId)}`,
      { headers },
    );

    if (getRes.status === 404) {
      // Already gone — nothing to do, client can retry login immediately
      return NextResponse.json({ status: "not_found" });
    }

    if (!getRes.ok) {
      const body = await getRes.text();
      console.error("[OneSignal resolve-identity] GET failed:", body);
      return NextResponse.json(
        { error: "Failed to fetch conflicting OneSignal user" },
        { status: 502 },
      );
    }

    // 2. Delete the conflicting user to free the external_id alias
    const delRes = await fetch(
      `${OS_BASE}/apps/${appId}/users/by/external_id/${encodeURIComponent(externalId)}`,
      { method: "DELETE", headers },
    );

    if (!delRes.ok && delRes.status !== 404) {
      const body = await delRes.text();
      console.error("[OneSignal resolve-identity] DELETE failed:", body);
      return NextResponse.json(
        { error: "Failed to delete conflicting OneSignal user" },
        { status: 502 },
      );
    }

    return NextResponse.json({ status: "resolved" });
  } catch (err) {
    console.error("[OneSignal resolve-identity] Unexpected error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
