import { createServerClient } from '@supabase/ssr'
import { NextRequest, NextResponse } from 'next/server'
import { safeRedirectPath } from '@/lib/auth/safe-redirect'

// tdd-guard:skip — OAuth callback route handler; safeRedirectPath is tested
// as a pure unit in lib/auth/__tests__/safe-redirect.test.ts (Batch 6 / SEC-004).

export async function GET(request: NextRequest) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get('code')
  const next = safeRedirectPath(searchParams.get('next'))

  if (code) {
    // Build the redirect response first so we can attach cookies to it.
    // Route Handlers must set cookies directly on the Response object —
    // using cookies() from next/headers in a Route Handler does not reliably
    // write to the outgoing response, so exchangeCodeForSession would succeed
    // but the session tokens would never reach the browser.
    const redirectResponse = NextResponse.redirect(`${origin}${next}`)

    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
      {
        cookies: {
          getAll() {
            return request.cookies.getAll()
          },
          setAll(cookiesToSet) {
            cookiesToSet.forEach(({ name, value, options }) => {
              redirectResponse.cookies.set(name, value, options)
            })
          },
        },
      }
    )

    const { error } = await supabase.auth.exchangeCodeForSession(code)
    if (!error) {
      return redirectResponse
    }
  }

  return NextResponse.redirect(`${origin}/login?error=auth_callback_error`)
}
