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

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

interface Game {
  id: string;
  away: string;
  home: string;
  start_time: string;
  sport: 'NBA' | 'MLB' | 'WNBA';
  status: 'scheduled' | 'live' | 'final';
  prop_count?: number;
  ab_grade_count?: number;
  injury_note?: string;
}

const VALID_SPORTS = new Set(['NBA', 'MLB', 'WNBA']);

export async function GET(req: NextRequest) {
  const sport = (req.nextUrl.searchParams.get('sport') || 'NBA').toUpperCase();
  if (!VALID_SPORTS.has(sport)) {
    return NextResponse.json({ error: 'Unknown sport.', games: [] }, { status: 400 });
  }

  try {
    const games = await cachedBackendJson<Game[]>(
      todayKey(sport, 'games'),
      sport,
      'games',
      `/api/games/tonight?sport=${sport}`,
      300,
    );
    return NextResponse.json(
      { games: Array.isArray(games) ? games : [] },
      { headers: { 'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600' } },
    );
  } catch {
    // The slate genuinely may be empty (off-day). Return empty list so the UI
    // shows the branded empty state instead of an error.
    return NextResponse.json({ games: [] });
  }
}
