/**
 * Credentials Route Tests
 *
 * Tests credential listing and encryption key rotation endpoints
 */

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

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

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

      expect(res.statusCode).toBe(200);
      expect(res.body.success).toBe(true);
      expect(Array.isArray(res.body.credentials)).toBe(true);
      expect(typeof res.body.count).toBe('number');
      expect(res.body.count).toBe(res.body.credentials.length);
    });
  });

  describe('POST /api/credentials/rotate-key', () => {
    test('should return 200 with success true', async () => {
      const res = await request(app)
        .post('/api/credentials/rotate-key')
        .send({});

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