import { NextRequest, NextResponse } from "next/server";
import { resolveGoogleAuth } from "@/lib/googleAuth";
import { withBase, googleCallbackUrl, COOKIE_PATH } from "@/lib/basePath";

/**
 * Begins the Google OAuth code flow (Story 5). Active once a Client ID is set —
 * in Admin Settings → Credentials → Google sign-in, or via env.
 */
export async function GET(req: NextRequest): Promise<NextResponse> {
  const { clientId } = await resolveGoogleAuth();
  if (!clientId) {
    return NextResponse.redirect(new URL(withBase("/login?error=google_not_configured"), req.url));
  }

  const redirectUri = googleCallbackUrl(req);
  const state = crypto.randomUUID();

  const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
  url.searchParams.set("client_id", clientId);
  url.searchParams.set("redirect_uri", redirectUri);
  url.searchParams.set("response_type", "code");
  url.searchParams.set("scope", "openid email profile");
  url.searchParams.set("state", state);
  url.searchParams.set("access_type", "online");
  url.searchParams.set("prompt", "select_account");

  const res = NextResponse.redirect(url.toString());
  res.cookies.set("g_state", state, { httpOnly: true, sameSite: "lax", path: COOKIE_PATH, maxAge: 600 });
  return res;
}
