/**
 * DC-106 + DC-108: Caddycode + Fleet endpoint tests
 */
const express = require('express');
const request = require('supertest');

function createCaddycodeApp() {
  const app = express();
  app.use(express.json());
  const routes = require('../../routes/caddycode');
  const wrap = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
  app.use('/api/v1', routes({ asyncHandler: wrap }));
  return app;
}

function createFleetApp(log) {
  const app = express();
  app.use(express.json());
  const routes = require('../../routes/fleet');
  const wrap = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
  app.use('/api/v1', routes({ log: log || { info: jest.fn(), warn: jest.fn(), error: jest.fn() }, asyncHandler: wrap }));
  return app;
}

describe('DC-106: Caddyfile-as-Code', () => {
  it('POST /generate creates Caddyfile from config', async () => {
    const app = createCaddycodeApp();
    const res = await request(app)
      .post('/api/v1/caddycode/generate')
      .send({
        domain: 'app.example.com',
        upstream: 'localhost:8080',
        websocket: true,
        cors: true,
      });

    expect(res.status).toBe(200);
    expect(res.body.caddyfile).toContain('app.example.com');
    expect(res.body.caddyfile).toContain('reverse_proxy');
    expect(res.body.caddyfile).toContain('Access-Control-Allow-Origin');
  });

  it('POST /generate returns 400 without domain', async () => {
    const app = createCaddycodeApp();
    const res = await request(app)
      .post('/api/v1/caddycode/generate')
      .send({ upstream: 'localhost:8080' });

    expect(res.status).toBe(400);
  });

  it('POST /validate finds unbalanced braces', async () => {
    const app = createCaddycodeApp();
    const res = await request(app)
      .post('/api/v1/caddycode/validate')
      .send({ caddyfile: 'app.com {\n reverse_proxy localhost:8080\n' });

    expect(res.status).toBe(200);
    expect(res.body.valid).toBe(false);
    expect(res.body.issues[0]).toContain('Unbalanced');
  });

  it('POST /validate passes for valid Caddyfile', async () => {
    const app = createCaddycodeApp();
    const res = await request(app)
      .post('/api/v1/caddycode/validate')
      .send({ caddyfile: 'app.com {\n  reverse_proxy localhost:8080\n}' });

    expect(res.status).toBe(200);
    expect(res.body.valid).toBe(true);
  });

  it('GET /templates returns preset configs', async () => {
    const app = createCaddycodeApp();
    const res = await request(app).get('/api/v1/caddycode/templates');

    expect(res.status).toBe(200);
    expect(Object.keys(res.body.templates).length).toBeGreaterThanOrEqual(5);
  });
});

describe('DC-108: Fleet Management', () => {
  beforeEach(() => {
    process.env.FLEET_HOSTS_FILE = `/tmp/fleet-test-${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
  });

  afterEach(() => {
    try { require('fs').unlinkSync(process.env.FLEET_HOSTS_FILE); } catch { /* ok */ }
  });

  it('GET /hosts returns empty list initially', async () => {
    const app = createFleetApp();
    const res = await request(app).get('/api/v1/fleet/hosts');
    expect(res.status).toBe(200);
    expect(res.body.total).toBe(0);
  });

  it('POST /hosts registers a new host', async () => {
      // DC-068: SSRF hardening rejects private-range IPv4 literals by default.
      // Use a public host literal to exercise the registration happy path.
      const app = createFleetApp();
      const res = await request(app)
        .post('/api/v1/fleet/hosts')
                .send({ name: 'Test Host', hostname: '8.8.8.8', port: 3001, apiKey: 'dk_test_12345', tags: ['prod'] });

      expect(res.status).toBe(201);
      expect(res.body.host.name).toBe('Test Host');
      expect(res.body.host.apiKey).toBe('***'); // Key is masked
      expect(res.body.host.apiKeyHash).toBeTruthy();
      expect(res.body.host.id).toBeTruthy();
    });

    it('POST /hosts returns 400 without name', async () => {
      const app = createFleetApp();
      const res = await request(app)
        .post('/api/v1/fleet/hosts')
        .send({ hostname: '8.8.8.8', port: 3001 });

      expect(res.status).toBe(400);
    });

    it('POST /deploy generates deployment plan', async () => {
      const app = createFleetApp();
      // First register a host (DC-068: use a public IPv4 since private IPs
      // are rejected by default).
      await request(app)
        .post('/api/v1/fleet/hosts')
        .send({ name: 'Host 1', hostname: '8.8.8.8', port: 3001 });

      const res = await request(app)
        .post('/api/v1/fleet/deploy')
        .send({ templateId: 'plex', config: { port: 32400 } });

      expect(res.status).toBe(200);
      expect(res.body.totalHosts).toBeGreaterThanOrEqual(1);
      expect(res.body.plan[0].templateId).toBe('plex');
    });
  });
