/**
 * Optional Pages Function: GET /api/site-stats → same payload as static JSON.
 * Prefer the static file at /api/site-stats.json; this route is a convenience
 * alias that tries to read the published asset when present.
 */
type PagesContext = {
  request: Request;
  env: Record<string, unknown>;
  waitUntil?: (p: Promise<unknown>) => void;
  next?: (input?: Request | string) => Promise<Response>;
  data?: unknown;
};

const JSON_HDR = {
  'content-type': 'application/json; charset=utf-8',
  'cache-control': 'public, max-age=0, must-revalidate',
};

export const onRequestGet = async (context: PagesContext): Promise<Response> => {
  try {
    const url = new URL(context.request.url);
    const assetUrl = new URL('/api/site-stats.json', url.origin);
    const res = await fetch(assetUrl.toString(), {
      headers: { Accept: 'application/json' },
    });
    if (res.ok) {
      const body = await res.text();
      return new Response(body, { status: 200, headers: JSON_HDR });
    }
  } catch { /* fall through */ }

  return new Response(
    JSON.stringify({
      unavailable: true,
      generatedAt: new Date().toISOString(),
    }),
    { status: 200, headers: JSON_HDR },
  );
};
