// src/tests/integration/system.integration.test.ts
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import supertest from 'supertest';

/**
 * @vitest-environment node
 */

describe('System API Routes Integration Tests', () => {
  let app: any;

  beforeAll(async () => {
    vi.stubEnv('FRONTEND_URL', 'https://example.com');
    app = (await import('../../../server')).default;
  });

  afterAll(() => {
    vi.unstubAllEnvs();
  });

  describe('GET /api/system/pm2-status', () => {
    it('should return a status for PM2', async () => {
      const request = supertest(app);
      // In a typical CI environment without PM2, this will fail gracefully.
      // The test verifies that the endpoint responds correctly, even if PM2 isn't running.
      const response = await request.get('/api/system/pm2-status');
      const result = response.body;
      expect(result).toBeDefined();

      // The response format depends on whether PM2 is available:
      // - If PM2 is available (200 OK): { success: true, data: { success: bool, message: string } }
      // - If PM2 command fails (500): { success: false, error: { code: string, message: string } }
      if (response.status === 200) {
        expect(result).toHaveProperty('success', true);
        expect(result).toHaveProperty('data');
        expect(result.data).toHaveProperty('message');
      } else {
        // Error response from global error handler
        expect(result).toHaveProperty('success', false);
        expect(result).toHaveProperty('error');
        expect(result.error).toHaveProperty('message');
      }
    });
  });
});
