/**
 * Error Log and Audit Log Route Tests
 *
 * Tests error log retrieval/clearing and audit log retrieval/clearing
 */

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

const testServicesFile = path.join(os.tmpdir(), `errorlogs-services-${Date.now()}.json`);
const testConfigFile = path.join(os.tmpdir(), `errorlogs-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('Error Log and Audit Log Routes', () => {
  afterAll(() => {
    try { fs.unlinkSync(testServicesFile); } catch (e) { /* ignore */ }
    try { fs.unlinkSync(testConfigFile); } catch (e) { /* ignore */ }
  });

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

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

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

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

  describe('DELETE /api/error-logs', () => {
    test('should return 200 with success message', async () => {
      const res = await request(app).delete('/api/error-logs');

      expect(res.statusCode).toBe(200);
      expect(res.body.success).toBe(true);
      expect(res.body).toHaveProperty('message');
    });
  });

  describe('DELETE /api/audit-logs', () => {
    test('should return 200 with success message', async () => {
      const res = await request(app).delete('/api/audit-logs');

      expect(res.statusCode).toBe(200);
      expect(res.body.success).toBe(true);
      expect(res.body).toHaveProperty('message');
    });
  });
});
