import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000';

/**
 * Preferences proxy (Session 49) — forwards GET/POST /api/preferences to the
 * Express route (which reads/writes Supabase user_metadata via the admin API).
 * Forwards the Authorization bearer so requireAuth can resolve the user.
 */
function authHeaders(req: NextRequest): HeadersInit {
  const auth = req.headers.get('authorization');
  return { Accept: 'application/json', 'Content-Type': 'application/json', ...(auth ? { Authorization: auth } : {}) };
}

export async function GET(req: NextRequest) {
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/preferences`, { method: 'GET', headers: authHeaders(req) });
    const data = await upstream.json().catch(() => ({}));
    return NextResponse.json(data, { status: upstream.status });
  } catch {
    return NextResponse.json({ error: 'Preferences service unreachable.' }, { status: 502 });
  }
}

export async function POST(req: NextRequest) {
  const body = await req.text();
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/preferences`, { method: 'POST', headers: authHeaders(req), body });
    const data = await upstream.json().catch(() => ({}));
    return NextResponse.json(data, { status: upstream.status });
  } catch {
    return NextResponse.json({ error: 'Preferences service unreachable.' }, { status: 502 });
  }
}
