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

export async function handleMetricsRequest(request: Request, db: Database): Promise<Response> {
  if (request.method !== 'GET') {
    return new Response('🚫 Method not allowed', { status: 405 });
  }
  if (!Metrics.enabled()) {
    return new Response('Metrics disabled', { status: 404 });
  }

  // Gauges de allowed_groups por estado (best-effort)
  try {
    const rows = db
      .prepare(`SELECT status, COUNT(*) AS c FROM allowed_groups GROUP BY status`)
      .all() as Array<{ status: string; c: number }>;
    let pending = 0, allowed = 0, blocked = 0;
    for (const r of rows) {
      const s = String(r?.status || '');
      const c = Number(r?.c || 0);
      if (s === 'pending') pending = c;
      else if (s === 'allowed') allowed = c;
      else if (s === 'blocked') blocked = c;
    }
    Metrics.set('allowed_groups_total_pending', pending);
    Metrics.set('allowed_groups_total_allowed', allowed);
    Metrics.set('allowed_groups_total_blocked', blocked);
  } catch {}

  // Exponer métrica con el tiempo restante hasta el próximo group sync (o -1 si scheduler inactivo)
  try {
    const secs = GroupSyncService.getSecondsUntilNextGroupSync();
    const val = (secs == null || !Number.isFinite(secs)) ? -1 : secs;
    Metrics.set('group_sync_seconds_until_next', val);
  } catch {}

  const format = (process.env.METRICS_FORMAT || 'prom').toLowerCase() === 'json' ? 'json' : 'prom';
  const body = Metrics.render(format as any);
  return new Response(body, {
    status: 200,
    headers: { 'Content-Type': format === 'json' ? 'application/json' : 'text/plain; version=0.0.4' }
  });
}
