import { NextRequest, NextResponse } from 'next/server';
import { cachedBackendJson, todayKey } from '@/services/odds-cache';

export const dynamic = 'force-dynamic';
export const revalidate = 300;

const VALID_SPORTS = new Set(['NBA', 'MLB', 'WNBA']);
const VALID_TIERS = new Set(['A', 'B', 'C', 'D']);

export async function GET(req: NextRequest) {
  const sport = (req.nextUrl.searchParams.get('sport') || '').toUpperCase();
  const tier = (req.nextUrl.searchParams.get('tier') || '').toUpperCase();
  const limit = Math.min(60, Math.max(1, Number(req.nextUrl.searchParams.get('limit') || 30)));

  if (sport && !VALID_SPORTS.has(sport)) return NextResponse.json({ entries: [] });
  if (tier && !VALID_TIERS.has(tier)) return NextResponse.json({ entries: [] });

  const params = new URLSearchParams();
  if (sport) params.set('sport', sport);
  if (tier) params.set('tier', tier);
  params.set('limit', String(limit));

  try {
    const data = await cachedBackendJson<{ entries: unknown[] }>(
      todayKey(sport || 'all', `ledger:${tier || 'all'}:${limit}`),
      sport || 'mixed',
      'ledger',
      `/api/ledger?${params}`,
      300,
    );
    return NextResponse.json({ entries: Array.isArray(data?.entries) ? data.entries : [] });
  } catch {
    return NextResponse.json({ entries: [] });
  }
}
