import { AutoReporter } from '../reporters/AutoReporter.js';
/**
 * Tests des nouveaux endpoints API
 */

const { describe, it, before, after } = require('node:test');
const assert = require('node:assert');
const { APIController } = require('../../lib/APIController');


// Auto-Reporter Configuration
const autoReporter = new AutoReporter();

describe('API Controller Tests', () => {
  let apiController;
  let mockReq, mockRes;

  before(() => {
    apiController = new APIController();

    // Mock response object
    mockRes = {
      json: (data) => { mockRes.lastResponse = data; },
      status: (code) => { mockRes.statusCode = code; return mockRes; },
      setHeader: () => {},
      send: (data) => { mockRes.lastSent = data; }
    };
  });

  it('Health endpoint should return system status', async () => {
    mockReq = {};

    await apiController.getHealth(mockReq, mockRes);

    assert.strictEqual(mockRes.lastResponse.success, true);
    assert.strictEqual(mockRes.lastResponse.data.status, 'healthy');
    assert.ok(mockRes.lastResponse.data.version);
    assert.ok(typeof mockRes.lastResponse.data.uptime === 'number');
  });

  it('Metrics endpoint should return system metrics', async () => {
    mockReq = {};

    await apiController.getMetrics(mockReq, mockRes);

    assert.strictEqual(mockRes.lastResponse.success, true);
    assert.ok(mockRes.lastResponse.data.articles);
    assert.ok(mockRes.lastResponse.data.projects);
    assert.ok(mockRes.lastResponse.data.templates);
    assert.ok(mockRes.lastResponse.data.system);
  });

  it('Create project should work with valid data', async () => {
    mockReq = {
      body: {
        name: 'Test Project API',
        description: 'Project créé via test API',
        config: {
          defaultPersonality: 'Marc'
        }
      }
    };

    await apiController.createProject(mockReq, mockRes);

    assert.strictEqual(mockRes.lastResponse.success, true);
    assert.strictEqual(mockRes.lastResponse.data.name, 'Test Project API');
    assert.ok(mockRes.lastResponse.data.id);
    assert.strictEqual(mockRes.lastResponse.data.articlesCount, 0);
  });

  it('Create project should fail without name', async () => {
    mockReq = {
      body: {
        description: 'Project sans nom'
      }
    };

    await apiController.createProject(mockReq, mockRes);

    assert.strictEqual(mockRes.statusCode, 400);
    assert.strictEqual(mockRes.lastResponse.success, false);
    assert.ok(mockRes.lastResponse.error.includes('Nom du projet requis'));
  });

  it('Create template should work with valid data', async () => {
    mockReq = {
      body: {
        name: 'Template Test',
        content: '<?xml version="1.0"?><template><title>Test</title></template>',
        description: 'Template de test',
        category: 'test'
      }
    };

    await apiController.createTemplate(mockReq, mockRes);

    assert.strictEqual(mockRes.lastResponse.success, true);
    assert.strictEqual(mockRes.lastResponse.data.name, 'Template Test');
    assert.ok(mockRes.lastResponse.data.id);
  });

  it('Get projects should return project list', async () => {
    mockReq = {};

    await apiController.getProjects(mockReq, mockRes);

    assert.strictEqual(mockRes.lastResponse.success, true);
    assert.ok(Array.isArray(mockRes.lastResponse.data.projects));
    assert.ok(typeof mockRes.lastResponse.data.total === 'number');
  });

  it('Get templates should return template list', async () => {
    mockReq = {};

    await apiController.getTemplates(mockReq, mockRes);

    assert.strictEqual(mockRes.lastResponse.success, true);
    assert.ok(Array.isArray(mockRes.lastResponse.data.templates));
    assert.ok(typeof mockRes.lastResponse.data.total === 'number');
  });

  it('Create article should validate input', async () => {
    mockReq = {
      body: {}
    };

    await apiController.createArticle(mockReq, mockRes);

    assert.strictEqual(mockRes.statusCode, 400);
    assert.strictEqual(mockRes.lastResponse.success, false);
    assert.ok(mockRes.lastResponse.error.includes('Mot-clé ou numéro de ligne requis'));
  });

  it('API should handle errors gracefully', async () => {
    // Test avec une méthode qui va échouer (getStoredArticle lève une exception)
    mockReq = {
      params: { id: 'invalid_id' },
      query: {}
    };

    await apiController.getArticle(mockReq, mockRes);

    // En cas d'erreur dans getStoredArticle, on retourne 500
    assert.strictEqual(mockRes.statusCode, 500);
    assert.strictEqual(mockRes.lastResponse.success, false);
    assert.ok(mockRes.lastResponse.error);
  });

  it('Response format should be consistent', async () => {
    mockReq = {};

    await apiController.getHealth(mockReq, mockRes);

    // Vérifier format standard de réponse
    assert.ok(mockRes.lastResponse.hasOwnProperty('success'));
    assert.ok(mockRes.lastResponse.hasOwnProperty('data'));
    assert.ok(typeof mockRes.lastResponse.success === 'boolean');
  });
});

console.log('✅ Tests API Controller - Validation des endpoints RESTful');