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

export const dynamic = 'force-dynamic';

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

/**
 * A1 S9 — Slip Reader proxy. Forwards POST /api/slips/parse (base64 image
 * or slip text) to Express with the Authorization header (S25 rule: the
 * browser never reaches Express directly). Body can be ~5MB of base64 —
 * stream it through as text.
 */
export async function POST(req: NextRequest) {
  const body = await req.text();
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/slips/parse`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(req.headers.get('authorization')
          ? { Authorization: req.headers.get('authorization')! }
          : {}),
      },
      body,
    });
    const data = await upstream.json().catch(() => ({}));
    return NextResponse.json(data, { status: upstream.status });
  } catch {
    return NextResponse.json({ error: 'The reader is offline. Try again shortly.' }, { status: 502 });
  }
}
