import { NextResponse } from "next/server";
import { buildAuthorizationUrl, createPkcePair, createState } from "@/lib/auth/google";
import {
  OAUTH_RETURN_COOKIE,
  OAUTH_STATE_COOKIE,
  OAUTH_VERIFIER_COOKIE,
  cookieSecurityOptions,
  googleOAuth,
} from "@/lib/auth/config";
import { hostIsSiteFirstParty } from "@/lib/seo/site";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/** Ten minutes is plenty to complete a consent screen. */
const HANDSHAKE_TTL_SECONDS = 600;

/**
 * Step 1 of Google sign-in: stash the CSRF state and the PKCE verifier in
 * short-lived httpOnly cookies, then hand the user to Google's consent screen.
 */
export async function GET(request: Request) {
  if (!googleOAuth.isConfigured) {
    return NextResponse.redirect(
      new URL("/auth/login?error=google_not_configured", request.url)
    );
  }

  const state = createState();
  const { verifier, challenge } = createPkcePair();

  const response = NextResponse.redirect(buildAuthorizationUrl(state, challenge));

  const cookieOptions = cookieSecurityOptions({ maxAge: HANDSHAKE_TTL_SECONDS });

  response.cookies.set(OAUTH_STATE_COOKIE, state, cookieOptions);
  response.cookies.set(OAUTH_VERIFIER_COOKIE, verifier, cookieOptions);

  // Remember where this sign-in started so the callback can send the user back
  // to the same host (e.g. app.scan-receipts.app) instead of always dropping
  // them on the main host. Only ever written for first-party hosts — never for
  // an arbitrary Origin — so no open redirect is possible.
  const returnHost = request.headers.get("host") || "";
  if (hostIsSiteFirstParty(returnHost)) {
    response.cookies.set(OAUTH_RETURN_COOKIE, returnHost, cookieOptions);
  }

  return response;
}
