import { NextResponse } from "next/server"
import { createClient } from "@/lib/supabase/server"

export const dynamic = 'force-dynamic';

export async function GET(request: Request) {
  try {
    // Extract search parameters and origin from the request URL
    const url = new URL(request.url)
    const searchParams = url.searchParams
    const origin = url.origin
 
    // Get the authorization code and the 'next' redirect path
    const code = searchParams.get("code")
    const next = searchParams.get("next") ?? "/"
 
    if (!code) {
      console.error("No code provided in callback")
      return NextResponse.redirect(`${origin}/auth/auth-code-error`)
    }

    // Create a Supabase client
    const supabase = createClient()
 
    // Exchange the code for a session
    const { error } = await supabase.auth.exchangeCodeForSession(code)
 
    if (error) {
      console.error("Error exchanging code for session:", error)
      return NextResponse.redirect(`${origin}/auth/auth-code-error`)
    }

    // If successful, redirect to the 'next' path or home
    return NextResponse.redirect(`${origin}${next}`)
  } catch (error) {
    console.error("Unexpected error in callback:", error)
    // Use a hardcoded fallback for origin in case of error
    const url = new URL(request.url)
    return NextResponse.redirect(`${url.origin}/auth/auth-code-error`)
  }
}