/**
 * GET  /api/auth/session — returns { user: session } or { user: null }
 * DELETE /api/auth/session — signs out (Supabase mode) or no-op (local mode)
 */

import { getSession, getAuthMode, getSupabaseAuthConfig } from '@/lib/auth.js';

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

export async function GET(req) {
  try {
    const session = await getSession(req);
    return Response.json({ user: session });
  } catch (err) {
    console.error('GET /api/auth/session error:', err);
    return Response.json({ user: null });
  }
}

export async function DELETE(req) {
  if (getAuthMode() === 'local') {
    return Response.json({ ok: true });
  }

  // Supabase mode: sign out via SSR client.
  try {
    // Build Supabase SSR client to call signOut.
    const { createServerClient } = await import('@supabase/ssr');
    const cookieHeader = req.headers.get('cookie') || '';

    const cookiesToSet = [];
    const { url: supabaseUrl, anonKey: supabaseAnonKey } = getSupabaseAuthConfig();
    const supabase = createServerClient(
      supabaseUrl,
      supabaseAnonKey,
      {
        cookies: {
          getAll() {
            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);
          },
        },
      }
    );

    await supabase.auth.signOut();
    const response = Response.json({ ok: true });
    for (const { name, value, options } of cookiesToSet) {
      response.headers.append(
        'Set-Cookie',
        `${name}=${value || ''}; Path=${options?.path || '/'}; Max-Age=${options?.maxAge ?? 0}; SameSite=${options?.sameSite || 'Lax'}${options?.httpOnly ? '; HttpOnly' : ''}${options?.secure ? '; Secure' : ''}`
      );
    }
    return response;
  } catch (err) {
    console.error('DELETE /api/auth/session error:', err);
    return Response.json({ ok: false, error: 'sign_out_failed' }, { status: 500 });
  }
}
