/* test/health.test.js
 *
 * Validates the /health route returns the right shape and status
 * codes for liveness and readiness.
 */
'use strict';

const assert = require('assert');
const { setupFreshDb } = require('./_setup');

const TESTS = [];
const test = (n, fn) => TESTS.push({ name: n, fn });

// Stub the global worker registry the health route reads
global.__ncii_workers = { caseDiscovery: 'running', takedown: 'running', autoEscalate: 'running' };

test('GET /health returns 200 when DB ok and workers running', () => {
  setupFreshDb();
  const router = require('../routes/health');
  // Use a fake req/res
  const req = {};
  const res = {
    statusCode: 200,
    body: null,
    status(c) { this.statusCode = c; return this; },
    json(b) { this.body = b; return this; },
  };
  // Seed an active Resend + Scrape.do key so readiness passes
  const apiKey = require('../models/apiKey');
  apiKey.create({ service: 'resend',    key_value: 're_ABCDEFGHIJ1234567890', label: 'h' });
  apiKey.create({ service: 'scrape_do', key_value: 'abcdef0123456789abcdef0123456789abcdef01', label: 'h' });
  apiKey.create({ service: 'MiniMax',  key_value: 'sk-cp-test1234', label: 'h' });

  router.handle({ ...req, url: '/', method: 'GET' }, res);
  assert.strictEqual(res.statusCode, 200, 'expected 200 ok');
  assert.strictEqual(res.body.status, 'ok');
  assert.strictEqual(res.body.workers.caseDiscovery, 'running');
  assert.ok(res.body.db === 'ok');
  assert.ok(res.body.keys.scrape_do.active >= 1);
});

test('GET /health returns 503 when no active Scrape.do key', () => {
  setupFreshDb();
  // No keys inserted
  const router = require('../routes/health');
  const res = { statusCode: 200, body: null, status(c) { this.statusCode = c; return this; }, json(b) { this.body = b; return this; } };
  router.handle({ url: '/', method: 'GET' }, res);
  assert.strictEqual(res.statusCode, 503, 'expected 503 degraded without active scrape_do key');
  assert.strictEqual(res.body.status, 'degraded');
});

test('GET /health/live always returns 200', () => {
  const router = require('../routes/health');
  const res = { statusCode: 200, body: null, status(c) { this.statusCode = c; return this; }, json(b) { this.body = b; return this; } };
  router.handle({ url: '/live', method: 'GET' }, res);
  assert.strictEqual(res.statusCode, 200);
  assert.strictEqual(res.body.status, 'ok');
});

test('GET /health/ready uses full readiness checks, not just DB', () => {
  setupFreshDb();
  const router = require('../routes/health');
  const res = { statusCode: 200, body: null, status(c) { this.statusCode = c; return this; }, json(b) { this.body = b; return this; } };
  router.handle({ url: '/ready', method: 'GET' }, res);
  assert.strictEqual(res.statusCode, 503, 'expected readiness to fail without active keys');
  assert.strictEqual(res.body.status, 'degraded');
  assert.ok(res.body.keys);
});

module.exports = TESTS;
