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

export const dynamic = 'force-dynamic';

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

/**
 * NBA odds proxy (Session 14).
 *
 * Forwards GET /api/odds/nba to the Express oddsService route of the
 * same shape, preserving the query string (stat_type / book filters
 * supported by the upstream `filterProps` step).
 *
 * Express already validates the sport key and consults the in-process
 * cache before hitting odds-api.com — the Next side is a thin pass-
 * through so the browser bundle never sees the ODDS_API_KEY.
 */
export async function GET(req: NextRequest) {
  const qs = req.nextUrl.search;
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/odds/nba${qs}`, {
      method: 'GET',
      headers: { Accept: 'application/json' },
    });
    const data = await upstream.json().catch(() => ({}));
    if (!upstream.ok) {
      return NextResponse.json(data, { status: upstream.status });
    }
    return NextResponse.json(data);
  } catch {
    return NextResponse.json(
      { error: 'Odds service is unreachable. Try again in a moment.' },
      { status: 502 },
    );
  }
}
