/**
 * GET /api/cron/heartbeat
 *
 * Manual / external-cron heartbeat for the payer-log KV layer.
 *
 * The primary heartbeat path is the SELF-HEARTBEAT inside recordPaidCall —
 * every paid call bumps the heartbeat key, so as long as paid traffic flows,
 * the /live freshness badge stays accurate without any cron at all.
 *
 * This route is kept as a backstop for two cases:
 *   1. Manual operator probe: `curl https://theloopbreaker.com/api/cron/heartbeat`
 *      to verify the data layer is alive when traffic is naturally idle.
 *   2. Optional external cron (cron-job.org, Pro-plan Vercel cron, etc.)
 *      — hit this every minute and the badge stays green even during
 *      zero-traffic windows.
 *
 * Security: when CRON_SECRET is set, the request must include
 * `Authorization: Bearer ${CRON_SECRET}`. Otherwise any GET is allowed
 * (useful for manual probing).
 *
 * No secrets in response. No PII. Read-safe.
 */

import { NextRequest, NextResponse } from 'next/server';
import { writeHeartbeat, readHeartbeat, isPersistenceConfigured } from '../../_lib/payer-log';

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

export async function GET(req: NextRequest): Promise<NextResponse> {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) {
    return NextResponse.json({ ok: false, error: 'cron authentication is not configured' }, { status: 503, headers: { 'Cache-Control': 'no-store' } });
  }
  const auth = req.headers.get('authorization');
  if (auth !== `Bearer ${cronSecret}`) {
    return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
  }

  if (!isPersistenceConfigured()) {
    return NextResponse.json(
      {
        ok: false,
        configured: false,
        message:
          'KV persistence not configured. Set KV_REST_API_URL and KV_REST_API_TOKEN ' +
          '(or UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN) in Vercel project env.',
      },
      { status: 503, headers: { 'Cache-Control': 'no-store' } },
    );
  }

  const writeOk = await writeHeartbeat();
  const readBack = await readHeartbeat();

  if (!writeOk || readBack === null) {
    return NextResponse.json(
      { ok: false, configured: true, error: 'heartbeat persistence write/read failed' },
      { status: 503, headers: { 'Cache-Control': 'no-store' } },
    );
  }

  return NextResponse.json(
    {
      ok: true,
      configured: true,
      writeOk,
      lastHeartbeat: readBack,
      lastHeartbeatIso: readBack ? new Date(readBack).toISOString() : null,
      ageMs: readBack ? Date.now() - readBack : null,
    },
    { status: 200 },
  );
}
