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

export const dynamic = 'force-dynamic';

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

/**
 * Schedule proxy (Session 25).
 *
 * The all-day intelligence endpoints (schedule / gamelines / streaks /
 * hotlist) were built on the Express backend in Sessions 23-24 but had
 * NO Next.js proxy route — so the browser's `fetch('/api/schedule/mlb')`
 * 404'd on the Next origin and the slate showed zero games even though
 * the backend was serving 8+. This thin forwarder fixes that, mirroring
 * the existing `/api/odds/*` proxies.
 */
export async function GET(req: NextRequest, { params }: { params: Promise<{ sport: string }> }) {
  const { sport } = await params;
  const sportLc = String(sport || '').toLowerCase();
  const qs = req.nextUrl.search;
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/schedule/${encodeURIComponent(sportLc)}${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 {
    // Schedule is the foundation layer — never blow up the page. Return an
    // empty-but-valid slate so the UI degrades to "no games" gracefully.
    return NextResponse.json({ sport: sportLc, games: [], source: 'espn' });
  }
}
