import { NextResponse } from 'next/server';

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

interface PublicStats {
  parlays_graded: number;
  kill_conditions_caught: number;
  a_grade_accuracy: number;
  last_updated: string;
}

const FALLBACK: PublicStats = {
  parlays_graded: 0,
  kill_conditions_caught: 0,
  a_grade_accuracy: 0,
  last_updated: new Date(0).toISOString(),
};

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

export async function GET(): Promise<NextResponse<PublicStats>> {
  try {
    const res = await fetch(`${BACKEND_URL}/api/stats/public`, {
      next: { revalidate: 30 },
      headers: { Accept: 'application/json' },
    });
    if (!res.ok) return NextResponse.json(FALLBACK, { headers: cache() });
    const data = (await res.json()) as Partial<PublicStats>;
    return NextResponse.json(
      {
        parlays_graded: Number(data.parlays_graded || 0),
        kill_conditions_caught: Number(data.kill_conditions_caught || 0),
        a_grade_accuracy: Number(data.a_grade_accuracy || 0),
        last_updated: data.last_updated || new Date().toISOString(),
      },
      { headers: cache() },
    );
  } catch {
    return NextResponse.json(FALLBACK, { headers: cache() });
  }
}

function cache() {
  return { 'Cache-Control': 'public, s-maxage=30, stale-while-revalidate=120' };
}
