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

export const dynamic = 'force-dynamic';

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

/**
 * Personal ledger proxy (Session 58, Phase 1) — forwards GET /api/ledger/mine
 * with the caller's Authorization header (Express requireAuth scopes rows to
 * the authenticated user).
 */
export async function GET(req: NextRequest) {
  const auth = req.headers.get('authorization');
  if (!auth) return NextResponse.json({ entries: [] }, { status: 401 });
  try {
    const qs = req.nextUrl.searchParams.toString();
    const upstream = await fetch(`${BACKEND_URL}/api/ledger/mine${qs ? `?${qs}` : ''}`, {
      headers: { Accept: 'application/json', Authorization: auth },
      cache: 'no-store',
    });
    const data = await upstream.json().catch(() => ({ entries: [] }));
    return NextResponse.json(data, { status: upstream.ok ? 200 : upstream.status });
  } catch {
    return NextResponse.json({ entries: [] }, { status: 200 });
  }
}
