
import { sanitizeInput, checkRateLimit, checkOrigin } from './security';
import assert from 'assert';

console.log("Running Security Manual Tests...");

// Helper for assertions
function test(name: string, fn: () => void) {
    try {
        fn();
        console.log(`✅ ${name}`);
    } catch (err: any) {
        console.error(`❌ ${name}`);
        console.error(err);
    }
}

// Tests
test('sanitizeInput: escapes HTML', () => {
    const input = '<script>alert(1)</script>';
    const output = sanitizeInput(input);
    assert.strictEqual(output, '&lt;script&gt;alert(1)&lt;/script&gt;');
});

test('sanitizeInput: recursive object sanitation', () => {
    const input = {
        name: '<b>Bold</b>',
        nested: { text: '"Quote"' },
        arr: ["'Single'"]
    };
    const output = sanitizeInput(input);
    assert.strictEqual(output.name, '&lt;b&gt;Bold&lt;/b&gt;');
    assert.strictEqual(output.nested.text, '&quot;Quote&quot;');
    assert.strictEqual(output.arr[0], '&#039;Single&#039;');
});

test('Rate Limiting: enforces limit', () => {
    const key = 'test-manual-ip';
    // Reset store for this key roughly (not possible via API, but we use unique key)
    checkRateLimit(key, 2, 1000); // 1st
    checkRateLimit(key, 2, 1000); // 2nd

    let threw = false;
    try {
        checkRateLimit(key, 2, 1000); // 3rd -> Should throw
    } catch (e: any) {
        threw = true;
        assert.strictEqual(e.code, 'TOO_MANY_REQUESTS');
    }
    assert.ok(threw, "Should have thrown TOO_MANY_REQUESTS");
});

test('CSRF: Check Origin', () => {
    // Mock ENV
    const originalUrl = process.env.VITE_PUBLIC_APP_URL;
    process.env.VITE_PUBLIC_APP_URL = 'https://leifo.fr';

    try {
        // Valid
        const validReq = { headers: { origin: 'https://leifo.fr' } };
        assert.strictEqual(checkOrigin(validReq), true);

        // Invalid
        const invalidReq = { headers: { origin: 'https://evil.com' } };
        assert.strictEqual(checkOrigin(invalidReq), false);

        // Localhost
        const localReq = { headers: { origin: 'http://localhost:3000' } };
        assert.strictEqual(checkOrigin(localReq), true);

    } finally {
        process.env.VITE_PUBLIC_APP_URL = originalUrl;
    }
});

console.log("Tests finished.");
