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

export const dynamic = 'force-dynamic';

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

// Frozen at the same set Express validates against
// (`src/services/oddsService.js SOCCER_SPORT_KEYS`). Duplicated here so
// a typo'd league bounces at the Next layer without burning a backend
// round-trip.
const VALID_LEAGUES = new Set([
  'wc', 'epl', 'laliga', 'bundesliga', 'seriea',
  'ligue1', 'ucl', 'mls', 'ligamx',
]);

export async function GET(req: NextRequest, { params }: { params: Promise<{ league: string }> }) {
  const { league } = await params;
  const leagueLc = String(league || '').toLowerCase();
  if (!VALID_LEAGUES.has(leagueLc)) {
    return NextResponse.json(
      { error: `Unknown soccer league. Valid: ${[...VALID_LEAGUES].join(', ')}.` },
      { status: 400 },
    );
  }

  // Pass the original query string through (filters: book, stat_type).
  const qs = req.nextUrl.search;
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/odds/soccer/${leagueLc}${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 },
    );
  }
}
