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

export const dynamic = 'force-dynamic';

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

/**
 * Public model-record proxy (Session 58, Phase 1) — forwards
 * GET /api/ledger/model (the pipeline's user_id-null rows + 30d aggregate).
 */
export async function GET(req: NextRequest) {
  try {
    const qs = req.nextUrl.searchParams.toString();
    const upstream = await fetch(`${BACKEND_URL}/api/ledger/model${qs ? `?${qs}` : ''}`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    });
    const data = await upstream.json().catch(() => ({ entries: [], aggregate: null }));
    return NextResponse.json(data, {
      status: upstream.ok ? 200 : upstream.status,
      headers: { 'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=120' },
    });
  } catch {
    return NextResponse.json({ entries: [], aggregate: null }, { status: 200 });
  }
}
