import { NextResponse } from "next/server";
import { loadSystemConfig } from "@/lib/system-config";
import crypto from "crypto";
import { cookies } from "next/headers";

export async function GET(request: Request) {
  try {
    const systemConfig = await loadSystemConfig();
    const { googleAuth } = systemConfig;

    if (!googleAuth?.clientId || !googleAuth?.clientSecret) {
      return NextResponse.json(
        { ok: false, message: "Google OAuth not configured" },
        { status: 400 }
      );
    }

    // Generate CSRF token
    const state = crypto.randomBytes(32).toString("hex");
    
    // Store state in cookie for verification
    const cookieStore = await cookies();
    cookieStore.set("oauth_state", state, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 600, // 10 minutes
    });

    // Build Google OAuth URL
    const params = new URLSearchParams({
      client_id: googleAuth.clientId,
      redirect_uri: `${process.env.APP_BASE_URL || "http://localhost:3001"}/auth/google/callback`,
      response_type: "code",
      scope: "openid email profile",
      state,
      access_type: "offline",
      prompt: "consent",
    });

    const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;

    return NextResponse.redirect(authUrl);
  } catch (error) {
    console.error("Google OAuth error:", error);
    return NextResponse.json(
      { ok: false, message: "Failed to initiate OAuth" },
      { status: 500 }
    );
  }
}
