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

/** Begin the Google OAuth code flow. Active once GOOGLE_CLIENT_ID is set. */
export async function GET(req: NextRequest): Promise<NextResponse> {
  const { clientId } = resolveGoogleAuth();
  if (!clientId) {
    return NextResponse.redirect(new URL(withBase("/login?error=google_off"), req.url));
  }

  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", googleCallbackUrl(req));
  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: "/", maxAge: 600 });
  return res;
}
