import { NextResponse } from "next/server";
import { generateState, generateCodeVerifier } from "arctic";
import { google } from "@/lib/oauth";

export const dynamic = "force-dynamic";

export async function GET() {
  const state = generateState();               // anti-CSRF nonce
  const codeVerifier = generateCodeVerifier(); // PKCE secret

  const authUrl = google.createAuthorizationURL(state, codeVerifier, [
    "openid", "email", "profile",
  ]);

  const res = NextResponse.redirect(authUrl);
  // Short-lived httpOnly cookies so the callback can verify the round-trip.
  const opts = {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax" as const,
    maxAge: 600, // 10 min
    path: "/",
  };
  res.cookies.set("g_state", state, opts);
  res.cookies.set("g_verifier", codeVerifier, opts);
  return res;
}
