import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { WebhookServer } from '../../../src/server';
import { Metrics } from '../../../src/services/metrics';
import { initializeDatabase } from '../../../src/db';
import { Database } from 'bun:sqlite';
import { setDb, resetDb } from '../../../src/db/locator';

import { toIsoSql as toIso } from '../../helpers/dates';

const envBackup = { ...process.env };
let memdb: Database;

describe('/metrics y /health (detallado)', () => {
  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test', METRICS_ENABLED: 'true' };
    Metrics.reset();
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    (WebhookServer as any).dbInstance = memdb;
    setDb(memdb);
  });

  afterEach(() => {
    process.env = envBackup;
    try { resetDb(); memdb.close(); } catch {}
  });

  test('/metrics devuelve métricas en formato Prometheus', async () => {
    // Sembrar algunas métricas
    Metrics.set('last_sync_ok', 1);
    Metrics.set('active_groups', 2);
    Metrics.inc('webhook_events_total_messages_upsert', 3);

    const res = await WebhookServer.handleRequest(new Request('http://localhost/metrics', { method: 'GET' }));
    expect(res.status).toBe(200);
    const body = await res.text();
    expect(body).toContain('last_sync_ok');
    expect(body).toContain('active_groups 2');
    expect(body).toContain('webhook_events_total_messages_upsert 3');
    expect(body).toContain('group_sync_seconds_until_next');
  });

  test('/health?full=1 devuelve JSON con contadores y snapshot', async () => {
    // Insertar datos
    memdb.exec(`INSERT INTO groups (id, community_id, name, active, last_verified) VALUES ('123@g.us','comm','Grupo 123',1, ?)`, toIso(new Date(Date.now() - 60_000)));
    memdb.exec(`INSERT INTO users (id) VALUES ('34600123456')`);
    memdb.exec(`INSERT INTO group_members (group_id, user_id, is_admin, is_active, first_seen_at, last_seen_at) VALUES ('123@g.us','34600123456',0,1,?,?)`,
      toIso(new Date()), toIso(new Date()));

    const res = await WebhookServer.handleRequest(new Request('http://localhost/health?full=1', { method: 'GET' }));
    expect(res.status).toBe(200);
    const json = await res.json();
    expect(json.status).toBe('ok');
    expect(typeof json.active_groups).toBe('number');
    expect(typeof json.active_members).toBe('number');
    // snapshot_age_ms debe ser null o un número >= 0
    if (json.snapshot_age_ms !== null) {
      expect(json.snapshot_age_ms).toBeGreaterThanOrEqual(0);
    }
  });
});
