import type { Database } from 'bun:sqlite';
import { Metrics } from '../services/metrics';

export async function handleHealthRequest(url: URL, db: Database): Promise<Response> {
  // /health?full=1 devuelve JSON con detalles
  if (url.searchParams.get('full') === '1') {
    try {
      const rowG = db.prepare(`SELECT COUNT(*) AS c, MAX(last_verified) AS lv FROM groups WHERE active = 1`).get() as { c?: number; lv?: string | null } | undefined;
      const rowM = db.prepare(`SELECT COUNT(*) AS c FROM group_members WHERE is_active = 1`).get() as { c?: number } | undefined;
      const active_groups = Number(rowG?.c || 0);
      const active_members = Number(rowM?.c || 0);
      const lv = rowG?.lv ? String(rowG.lv) : null;
      let last_sync_at: string | null = lv;
      let snapshot_age_ms: number | null = null;
      if (lv) {
        const iso = lv.includes('T') ? lv : (lv.replace(' ', 'T') + 'Z');
        const ms = Date.parse(iso);
        if (Number.isFinite(ms)) {
          snapshot_age_ms = Date.now() - ms;
        }
      }
      const lastSyncMetric = Metrics.get('last_sync_ok');
      const maxAgeRaw = Number(process.env.MAX_MEMBERS_SNAPSHOT_AGE_MS);
      const maxAgeMs = Number.isFinite(maxAgeRaw) && maxAgeRaw > 0 ? maxAgeRaw : 24 * 60 * 60 * 1000;
      const snapshot_fresh = typeof snapshot_age_ms === 'number' ? (snapshot_age_ms <= maxAgeMs) : false;
      let last_sync_ok: number;
      if (typeof lastSyncMetric === 'number') {
        last_sync_ok = (lastSyncMetric === 1 && snapshot_fresh) ? 1 : 0;
      } else {
        // Si no hay métrica explícita, nos basamos exclusivamente en la frescura de la snapshot
        last_sync_ok = snapshot_fresh ? 1 : 0;
      }
      const payload = { status: 'ok', active_groups, active_members, last_sync_at, snapshot_age_ms, snapshot_fresh, last_sync_ok };
      return new Response(JSON.stringify(payload), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    } catch (e) {
      return new Response(JSON.stringify({ status: 'error' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
  }
  return new Response('OK', { status: 200 });
}
