import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { buildLinkedInAuthUrl, createOAuthState } from "@/lib/auth/linkedin";
import { ensureProjectForOAuth } from "@/lib/db/assert-project";
import { getSocialLinkedInRedirectUri, getLinkedInConfig } from "@/lib/env";
import { linkedInScopesErrorMessage } from "@/lib/social/linkedin-scopes";
import { setOAuthCookies } from "@/lib/social/oauth-cookies";

const PREFIX = "linkedin";

/** Start LinkedIn OAuth for a project connected account (not app user login). */
export async function GET(request: Request) {
  try {
    const user = await getSessionUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get("projectId");
    const returnTo = searchParams.get("return") ?? "/connected-accounts";
    const reconnect = searchParams.get("reconnect") === "1";

    if (!projectId) {
      return NextResponse.json(
        { error: "projectId is required to connect a social account." },
        { status: 400 },
      );
    }

    await ensureProjectForOAuth({
      projectId,
      userId: user.id,
      email: user.email,
      name: user.name,
    });

    const { scopeValidation } = getLinkedInConfig();
    if (!scopeValidation.valid) {
      return NextResponse.json(
        { error: linkedInScopesErrorMessage(scopeValidation) },
        { status: 500 },
      );
    }

    const state = createOAuthState();
    const url = buildLinkedInAuthUrl(state, getSocialLinkedInRedirectUri(), reconnect);
    const response = NextResponse.redirect(url);
    setOAuthCookies(response, PREFIX, {
      state,
      projectId,
      platform: "linkedin",
      returnTo,
    });

    return response;
  } catch (error) {
    const message = error instanceof Error ? error.message : "OAuth failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
