const { test } = require('node:test');
const assert = require('node:assert/strict');
const EventEmitter = require('node:events');

const { metricsHandler, metricsMiddleware, register } = require('../src/utils/metrics');

test('metrics middleware records HTTP request counters and durations', async () => {
  const req = {
    method: 'GET',
    path: '/api/encounters/123',
    url: '/api/encounters/123',
    baseUrl: '',
    route: null
  };
  const res = new EventEmitter();
  res.statusCode = 200;

  await new Promise((resolve) => metricsMiddleware(req, res, resolve));
  res.emit('finish');

  const metrics = await register.metrics();
  assert.match(metrics, /ped_ai_http_requests_total/);
  assert.match(metrics, /route="\/api\/encounters\/:id"/);
  assert.match(metrics, /ped_ai_http_request_duration_seconds_count/);
});

test('metrics middleware uses the first path for Express array routes', async () => {
  const req = {
    method: 'GET',
    path: '/',
    url: '/',
    baseUrl: '',
    route: { path: ['/', '/index.html'] }
  };
  const res = new EventEmitter();
  res.statusCode = 200;

  await new Promise((resolve) => metricsMiddleware(req, res, resolve));
  res.emit('finish');

  const metrics = await register.metrics();
  assert.match(metrics, /route="\/"/);
  assert.doesNotMatch(metrics, /route="\/,\/index\.html"/);
});

test('metrics middleware collapses unmatched 404 routes', async () => {
  const req = {
    method: 'GET',
    path: '/wp-content/plugins/example.php',
    url: '/wp-content/plugins/example.php?probe=1',
    baseUrl: '',
    route: null
  };
  const res = new EventEmitter();
  res.statusCode = 404;

  await new Promise((resolve) => metricsMiddleware(req, res, resolve));
  res.emit('finish');

  const metrics = await register.metrics();
  assert.match(metrics, /route="unmatched"/);
  assert.doesNotMatch(metrics, /wp-content\/plugins\/example\.php/);
});

test('metrics handler exposes prometheus content type', async () => {
  const headers = {};
  const res = {
    body: '',
    setHeader: function(name, value) { headers[name] = value; },
    end: function(body) { this.body = body; }
  };

  await metricsHandler({}, res);

  assert.equal(headers['Content-Type'], register.contentType);
  assert.match(res.body, /ped_ai_process_cpu_user_seconds_total/);
});
