import { NextRequest, NextResponse } from "next/server";
import { randomBytes } from "crypto";
import { buildAuthorizationUrl, isOAuthProvider, OAUTH_STATE_COOKIE } from "@/lib/oauth";
import { getBaseUrl } from "@/lib/email";

/** Start the social sign-in flow: set a CSRF state cookie and bounce to the provider. */
export async function GET(req: NextRequest, { params }: { params: Promise<{ provider: string }> }) {
  const { provider } = await params;
  // Behind the Apache proxy req.url is localhost — build redirects from the public base URL.
  const base = await getBaseUrl();
  if (!isOAuthProvider(provider)) {
    return NextResponse.redirect(new URL("/login?error=Unknown%20sign-in%20provider", base));
  }

  const role = req.nextUrl.searchParams.get("role") === "organizer" ? "organizer" : "attendee";
  const next = req.nextUrl.searchParams.get("next") ?? "";
  const nonce = randomBytes(16).toString("hex");
  const state = `${nonce}.${role}.${Buffer.from(next).toString("base64url")}`;

  const authUrl = await buildAuthorizationUrl(provider, state);
  if (!authUrl) {
    return NextResponse.redirect(new URL(`/login?error=${encodeURIComponent("That sign-in method is not configured yet.")}`, base));
  }

  const res = NextResponse.redirect(authUrl);
  res.cookies.set(OAUTH_STATE_COOKIE, state, {
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    maxAge: 600,
    path: "/",
  });
  return res;
}
