/**
 * GET /api/auth/callback — Supabase OAuth / magic-link callback handler.
 *
 * Reads the `code` query param, exchanges it for a session via the Supabase
 * SSR client, then redirects to / on success or /login?error=oauth_failed on
 * failure.
 *
 * In local mode this route is effectively unreachable (the login page
 * short-circuits before Supabase is involved), but it is safe to import.
 */

import { NextResponse } from 'next/server';
import { getAuthMode, getSupabaseAuthConfig } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(req) {
  const { searchParams, origin } = new URL(req.url);
  const code = searchParams.get('code');
  const next = searchParams.get('next') ?? '/';

  if (getAuthMode() === 'local') {
    // Local dev: nothing to exchange — redirect straight to dashboard.
    return NextResponse.redirect(new URL('/', origin));
  }

  if (!code) {
    console.warn('[auth/callback] No code param received — redirecting to login.');
    return NextResponse.redirect(new URL('/login?error=oauth_failed', origin));
  }

  try {
    const { createServerClient } = await import('@supabase/ssr');

    // We need to be able to set cookies in the response for the session.
    const responseHeaders = new Headers();
    const cookiesToSet = [];

    const { url: supabaseUrl, anonKey: supabaseAnonKey } = getSupabaseAuthConfig();
    const supabase = createServerClient(
      supabaseUrl,
      supabaseAnonKey,
      {
        cookies: {
          getAll() {
            const cookieHeader = req.headers.get('cookie') || '';
            return cookieHeader
              .split(';')
              .map((c) => c.trim())
              .filter(Boolean)
              .map((c) => {
                const idx = c.indexOf('=');
                return { name: c.slice(0, idx), value: c.slice(idx + 1) };
              });
          },
          setAll(cookies) {
            cookiesToSet.push(...cookies);
          },
        },
      }
    );

    const { error } = await supabase.auth.exchangeCodeForSession(code);

    if (error) {
      console.error('[auth/callback] exchangeCodeForSession error:', error.message);
      return NextResponse.redirect(new URL('/login?error=oauth_failed', origin));
    }

    // Build the redirect response and attach Set-Cookie headers.
    const redirectUrl = new URL(next.startsWith('/') ? next : '/', origin);
    const response = NextResponse.redirect(redirectUrl);

    for (const { name, value, options } of cookiesToSet) {
      response.cookies.set(name, value, options ?? {});
    }

    return response;
  } catch (err) {
    console.error('[auth/callback] Unexpected error:', err);
    return NextResponse.redirect(new URL('/login?error=oauth_failed', origin));
  }
}
