import { NextResponse } from "next/server"
import { createClient } from "@/lib/supabase/server"
import { ensureUserProfile } from "@/lib/auth/ensure-user-profile"

export async function GET(request: Request) {
  const requestUrl = new URL(request.url)
  const code = requestUrl.searchParams.get("code")
  let next = requestUrl.searchParams.get("next") ?? "/dashboard"
  const forwardedHost = request.headers.get("x-forwarded-host")
  const forwardedProto = request.headers.get("x-forwarded-proto") ?? "https"
  const isDevelopment = process.env.NODE_ENV === "development"
  const resolvedOrigin =
    !isDevelopment && forwardedHost ? `${forwardedProto}://${forwardedHost}` : requestUrl.origin

  if (!next.startsWith("/")) {
    next = "/dashboard"
  }

  const redirectToError = () => NextResponse.redirect(`${resolvedOrigin}/auth/error`)

  if (!code) {
    return redirectToError()
  }

  const supabase = await createClient()
  const { error: exchangeError } = await supabase.auth.exchangeCodeForSession(code)
  if (exchangeError) {
    return redirectToError()
  }

  const {
    data: { user },
    error: userError,
  } = await supabase.auth.getUser()

  if (userError || !user) {
    return redirectToError()
  }

  const ensureResult = await ensureUserProfile(supabase, user)
  if (!ensureResult.ok) {
    return redirectToError()
  }

  return NextResponse.redirect(`${resolvedOrigin}${next}`)
}
