import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { ensureProjectForOAuth } from "@/lib/db/assert-project";
import { getPlatformBlockReason } from "@/lib/social/config/social-config";
import { resolvePlatformCountryAvailability } from "@/lib/social/config/platform-availability";
import { createOAuthState, setOAuthCookies } from "@/lib/social/oauth-cookies";
import { buildThreadsAuthUrl } from "@/lib/social/threads-oauth";
import { getUserProjects } from "@/lib/storage/projects";

const PREFIX = "threads";

export async function GET(request: Request) {
  try {
    const user = await getSessionUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const blocked = getPlatformBlockReason("threads");
    if (blocked) {
      return NextResponse.json(
        { error: blocked.message, code: blocked.code, action: blocked.action },
        { status: 403 },
      );
    }

    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get("projectId");
    const returnTo = searchParams.get("return") ?? "/connected-accounts";
    if (!projectId) {
      return NextResponse.json({ error: "projectId is required" }, { status: 400 });
    }

    const snapshot = await getUserProjects(user.id);
    const project = snapshot?.projects.find((p) => p.id === projectId);
    const countryGate = resolvePlatformCountryAvailability(
      "threads",
      project?.countries,
    );
    if (!countryGate.available) {
      return NextResponse.json(
        {
          error: countryGate.message,
          code: countryGate.reason.toUpperCase(),
          action: "Choose a supported region or another platform",
        },
        { status: 403 },
      );
    }

    await ensureProjectForOAuth({
      projectId,
      userId: user.id,
      email: user.email,
      name: user.name,
    });

    const state = createOAuthState();
    const url = buildThreadsAuthUrl(state);
    const response = NextResponse.redirect(url);
    setOAuthCookies(response, PREFIX, {
      state,
      projectId,
      platform: "threads",
      returnTo,
    });
    return response;
  } catch (error) {
    const message = error instanceof Error ? error.message : "Threads OAuth failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
