import { NextResponse } from 'next/server';

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

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

interface LiveProp {
  player: string;
  stat: string;
  line: number;
  direction: 'over' | 'under';
  grade: string;
  confidence: number;
  sport: 'NBA' | 'MLB' | 'WNBA';
  graded_at: string;
}

export async function GET(): Promise<NextResponse<LiveProp[] | { error: string }>> {
  try {
    const res = await fetch(`${BACKEND_URL}/api/props/live`, {
      next: { revalidate: 60 },
      headers: { Accept: 'application/json' },
    });

    if (!res.ok) {
      // Backend unavailable — return empty list, the UI shows the fallback line.
      return NextResponse.json([], { status: 200, headers: cacheHeaders() });
    }

    const data = (await res.json()) as LiveProp[];
    if (!Array.isArray(data)) {
      return NextResponse.json([], { status: 200, headers: cacheHeaders() });
    }
    return NextResponse.json(data.slice(0, 24), { headers: cacheHeaders() });
  } catch {
    return NextResponse.json([], { status: 200, headers: cacheHeaders() });
  }
}

function cacheHeaders() {
  return { 'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300' };
}
