/**
 * Container Route Tests
 *
 * Tests Docker container management endpoints (start, stop, restart, discover)
 */

const request = require('supertest');
const fs = require('fs');
const path = require('path');
const os = require('os');

const testServicesFile = path.join(os.tmpdir(), `containers-services-${Date.now()}.json`);
const testConfigFile = path.join(os.tmpdir(), `containers-config-${Date.now()}.json`);

process.env.SERVICES_FILE = testServicesFile;
process.env.CONFIG_FILE = testConfigFile;
process.env.ENABLE_HEALTH_CHECKER = 'false';
process.env.NODE_ENV = 'test';

fs.writeFileSync(testServicesFile, '[]', 'utf8');
fs.writeFileSync(testConfigFile, '{}', 'utf8');

const app = require('../server');

describe('Container Routes', () => {
  afterAll(() => {
    try { fs.unlinkSync(testServicesFile); } catch (e) { /* ignore */ }
    try { fs.unlinkSync(testConfigFile); } catch (e) { /* ignore */ }
  });

  describe('POST /api/containers/:id/start', () => {
    test('should return error for invalid container ID', async () => {
      const res = await request(app)
        .post('/api/containers/nonexistent-container-id/start');

      // Docker will reject the invalid container ID with an error
      expect(res.statusCode).toBeGreaterThanOrEqual(400);
      expect(res.body.success).toBe(false);
    });
  });

  describe('POST /api/containers/:id/stop', () => {
    test('should return error for invalid container ID', async () => {
      const res = await request(app)
        .post('/api/containers/nonexistent-container-id/stop');

      // Docker will reject the invalid container ID with an error
      expect(res.statusCode).toBeGreaterThanOrEqual(400);
      expect(res.body.success).toBe(false);
    });
  });

  describe('POST /api/containers/:id/restart', () => {
    test('should return error for invalid container ID', async () => {
      const res = await request(app)
        .post('/api/containers/nonexistent-container-id/restart');

      // Docker will reject the invalid container ID with an error
      expect(res.statusCode).toBeGreaterThanOrEqual(400);
      expect(res.body.success).toBe(false);
    });
  });

  describe('GET /api/containers/discover', () => {
    test('should return 200 with containers array', async () => {
      const res = await request(app).get('/api/containers/discover');

      expect(res.statusCode).toBe(200);
      expect(res.body.success).toBe(true);
      expect(Array.isArray(res.body.containers)).toBe(true);
    });
  });
});
