/**
 * Phase 3b — verify createGatewayApp mounts /metrics with no auth and
 * returns Prometheus text format.
 */
import { describe, it, expect } from 'vitest';
import request from 'supertest';
import { Registry } from 'prom-client';
import { createGatewayApp } from './server.js';
import { createGatewayMetrics } from '../metrics/gateway-metrics.js';
import type { GatewayConfig } from './config.js';
import type { BackendStatusRegistry } from '../engine/backend-status-registry.js';

function makeRegistry(): BackendStatusRegistry {
  return {
    start: () => {},
    stop: async () => {},
    getAll: () => [],
    getByNodeId: () => null,
    subscribe: () => () => {},
    refresh: async () => {},
  } as unknown as BackendStatusRegistry;
}

function makeConfig(): GatewayConfig {
  return {
    enabled: true,
    listenPort: 4000,
    requestTimeoutSec: 600,
    upstreamTimeoutSec: 30,
    shutdownGracefulSec: 30,
    backends: [{ id: 'gpu-a', endpoint: 'http://upstream', model: 'qwen3:8b', maxSlots: 1 }],
    virtualKeys: [{ key: 'sk-aao-test', team: 'alpha' }],
    metrics: { enabled: true, prefix: 'aao_gateway' },
  };
}

describe('/metrics endpoint', () => {
  it('returns 200 + text/plain Prometheus format with no auth', async () => {
    const reg = new Registry();
    const metrics = createGatewayMetrics(reg, 'aao_gateway_e');
    const { app } = createGatewayApp({
      config: makeConfig(),
      registry: makeRegistry(),
      metrics,
      metricsRegistry: reg,
    });
    const res = await request(app).get('/metrics');
    expect(res.status).toBe(200);
    expect(res.headers['content-type']).toMatch(/^text\/plain.*version=0\.0\.4/);
    expect(res.text).toContain('aao_gateway_e_requests_total');
  });

  it('is not mounted when metricsRegistry is omitted', async () => {
    const { app } = createGatewayApp({
      config: makeConfig(),
      registry: makeRegistry(),
    });
    const res = await request(app).get('/metrics');
    // Falls through to the generic 404 in server.ts
    expect(res.status).toBe(404);
  });

  it('does not require Authorization header', async () => {
    const reg = new Registry();
    createGatewayMetrics(reg, 'aao_gateway_e2');
    const { app } = createGatewayApp({
      config: makeConfig(),
      registry: makeRegistry(),
      metricsRegistry: reg,
    });
    const res = await request(app).get('/metrics'); // no Authorization
    expect(res.status).toBe(200);
  });
});
