import assert from 'node:assert/strict';
import {access, readFile} from 'node:fs/promises';
import {createRequire} from 'node:module';

const require = createRequire(import.meta.url);

const vitiAssets = JSON.parse(await readFile(
    new URL('../../assets/package.json', import.meta.url),
    'utf8',
));
assert.equal(
    vitiAssets.symfony.controllers['captcha-spam-filter'].main,
    'controllers/captcha-spam-filter_controller.js',
);
assert.equal(vitiAssets.peerDependencies['@cpcreation/altcha-bundle'], '0.1.0');
assert.equal(vitiAssets.peerDependencies.altcha, undefined);

const compatibilityController = new URL(
    '../../assets/controllers/captcha-spam-filter_controller.js',
    import.meta.url,
);
await access(compatibilityController);
assert.match(
    await readFile(compatibilityController, 'utf8'),
    /from ['"]@cpcreation\/altcha-bundle\/controllers\/altcha_controller\.js['"]/u,
    'Le contrôleur historique doit déléguer au bundle sans réembarquer ALTCHA.',
);

const bundleAssets = JSON.parse(await readFile(
    require.resolve('@cpcreation/altcha-bundle/package.json'),
    'utf8',
));
assert.equal(bundleAssets.peerDependencies.altcha, '3.2.2');
assert.equal(bundleAssets.symfony.controllers.altcha.name, 'cpcreation-altcha');

const contactComponent = await readFile(new URL(
    '../../src/Bridge/Symfony/Bundle/Twig/Components/Site/ContactForm.php',
    import.meta.url,
), 'utf8');
assert.doesNotMatch(
    contactComponent,
    /dispatchBrowserEvent\(\s*['"](?:cpcreation-altcha:reset|viti:captcha-reset)['"]\s*\)/u,
    'Le formulaire de contact doit laisser le bundle réinitialiser ALTCHA après l’action finale.',
);

for (const templateName of ['RegisterConfirmForm', 'ResetPasswordForm']) {
    const template = await readFile(new URL(
        `../../src/Bridge/Symfony/Bundle/Resources/views/components/security/${templateName}.html.twig`,
        import.meta.url,
    ), 'utf8');

    assert.match(
        template,
        /['"]data-model['"]:\s*['"]norender\|\*['"]/u,
        `${templateName} doit conserver la preuve ALTCHA côté client jusqu'à la soumission finale.`,
    );
    assert.doesNotMatch(
        template,
        /['"]data-model['"]:\s*['"]on\(input\)\|\*['"]/u,
        `${templateName} ne doit pas déclencher un rendu LiveComponent lors de la résolution ALTCHA.`,
    );
}

const paymentTemplate = await readFile(new URL(
    '../../src/Bridge/Symfony/Bundle/Resources/views/components/payment/Form.html.twig',
    import.meta.url,
), 'utf8');
assert.match(paymentTemplate, /form_row\(form\.captcha\)/u);
assert.match(paymentTemplate, /['"]data-model['"]:\s*['"]norender\|\*['"]/u);
assert.match(paymentTemplate, /['"]data-live-action-param['"]:\s*['"]submitPayment['"]/u);

console.log('OK — VitiCore délègue le widget et son cycle LiveComponent au bundle ALTCHA.');
