/**
 * Test pour la résolution d'école
 * 
 * Ce fichier teste les fonctionnalités de sécurité et de validation
 * de l'endpoint /api/schools/resolve
 */

const assert = require('assert');

describe('School Resolution Security Tests', () => {

    describe('Input Validation', () => {
        it('should reject missing identifier', async () => {
            const response = await sails.helpers.http.get('/api/schools/resolve');
            assert.strictEqual(response.statusCode, 400);
            assert(response.body.error === 'INVALID_IDENTIFIER');
        });

        it('should reject invalid format (not E + 5 digits)', async () => {
            const testCases = [
                'E1234',    // Trop court
                'E123456',  // Trop long
                'A12345',   // Mauvais préfixe
                '12345',    // Pas de préfixe
                'E12ABC',   // Caractères non numériques
                'E00000',   // Valide
                'E99999'    // Valide
            ];

            for (const testCase of testCases) {
                const response = await sails.helpers.http.get(`/api/schools/resolve?identifier=${testCase}`);

                if (testCase.match(/^E\d{5}$/)) {
                    // Format valide
                    assert(response.statusCode === 200 || response.statusCode === 404);
                } else {
                    // Format invalide
                    assert.strictEqual(response.statusCode, 400);
                    assert(response.body.error === 'INVALID_FORMAT');
                }
            }
        });
    });

    describe('Rate Limiting', () => {
        it('should enforce rate limits', async () => {
            const clientIP = '192.168.1.100';

            // Simuler plusieurs requêtes rapides
            const promises = [];
            for (let i = 0; i < 15; i++) {
                promises.push(
                    sails.helpers.http.get('/api/schools/resolve?identifier=E00001', {
                        headers: { 'X-Forwarded-For': clientIP }
                    })
                );
            }

            const responses = await Promise.all(promises);

            // Vérifier que certaines requêtes sont bloquées par le rate limiting
            const rateLimited = responses.filter(r => r.statusCode === 429);
            assert(rateLimited.length > 0, 'Rate limiting should block some requests');
        });
    });

    describe('School Resolution', () => {
        it('should return 404 for non-existent school', async () => {
            const response = await sails.helpers.http.get('/api/schools/resolve?identifier=E99999');
            assert.strictEqual(response.statusCode, 404);
            assert(response.body.error === 'SCHOOL_NOT_FOUND');
        });

        it('should return school info for valid identifier', async () => {
            // Test avec une école existante (ajuster selon votre config)
            const response = await sails.helpers.http.get('/api/schools/resolve?identifier=E00001');

            if (response.statusCode === 200) {
                const data = response.body.data;
                assert(data.identifier === 'E00001');
                assert(typeof data.name === 'string');
                assert(typeof data.apiBaseUrl === 'string');
                assert(data.apiBaseUrl.startsWith('https://'));

                // Vérifier qu'aucune information sensible n'est exposée
                assert(!data.hasOwnProperty('apiKey'));
                assert(!data.hasOwnProperty('secret'));
                assert(!data.hasOwnProperty('database'));
            }
        });
    });

    describe('Security Headers', () => {
        it('should not expose sensitive information in headers', async () => {
            const response = await sails.helpers.http.get('/api/schools/resolve?identifier=E00001');

            const sensitiveHeaders = ['x-powered-by', 'server', 'x-aspnet-version'];
            for (const header of sensitiveHeaders) {
                assert(!response.headers[header], `Should not expose ${header} header`);
            }
        });
    });
});
