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

export const dynamic = 'force-dynamic';

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

/**
 * Parlay Lab grade proxy (Session 50) — forwards POST /api/parlay/grade to the
 * Express correlation model. Public + stateless (the Lab UI is tier-gated on the
 * frontend); body carries { legs, betAmount }.
 */
export async function POST(req: NextRequest) {
  const body = await req.text();
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/parlay/grade`, {
      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 engine hit a wall on this parlay.' }, { status: 502 });
  }
}
