// GET /api/google/oauth/connect
// Lance le flow OAuth Google : pose un cookie de state CSRF, redirige vers Google.

import { NextResponse } from "next/server";
import { randomBytes } from "node:crypto";
import { cookies } from "next/headers";
import { requireAdmin } from "@/lib/auth/server";
import { buildConsentUrl } from "@/lib/google-oauth";

const STATE_COOKIE = "novelia_google_oauth_state";

export async function GET() {
  await requireAdmin();

  // Nonce signe via le secret Better Auth pour proteger CSRF.
  const state = randomBytes(24).toString("hex");

  const url = buildConsentUrl(state);

  const cookieStore = await cookies();
  cookieStore.set(STATE_COOKIE, state, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    maxAge: 600, // 10 min pour completer le flow
    path: "/",
  });

  return NextResponse.redirect(url);
}
