import { getAuth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  try {
    const auth = await getAuth();
    const response = await auth.handler(req);
    
    // Get redirect URL from query params if provided
    const redirectUrl = req.nextUrl.searchParams.get("redirect") || "/account/webinars";
    
    // If response is a redirect, extract location and modify it
    if (response.status >= 300 && response.status < 400) {
      const location = response.headers.get("location");
      if (location) {
        // If it's redirecting to a callback page, preserve the redirect param
        return NextResponse.redirect(new URL(`/auth-callback?redirect=${encodeURIComponent(redirectUrl)}`, req.url));
      }
    }
    
    // Otherwise return auth response as is, then frontend will handle redirect
    return response;
  } catch (error) {
    console.error("Google callback error:", error);
    return new Response("Authentication failed", { status: 500 });
  }
}

