import assert from "node:assert/strict";
import { readFile, stat } from "node:fs/promises";
import test from "node:test";

const themeFile = (path) =>
    readFile(new URL(`../../${path}`, import.meta.url), "utf8");

const [
    template,
    frenchMessages,
    englishMessages,
    frenchMeta,
    englishMeta,
    backgroundImage,
] = await Promise.all([
    themeFile("templates/bundles/TwigBundle/Exception/error404.html.twig"),
    themeFile("translations/messages.fr.yaml"),
    themeFile("translations/messages.en.yaml"),
    themeFile("translations/meta.fr.yaml"),
    themeFile("translations/meta.en.yaml"),
    stat(
        new URL(
            "../../public/images/photo-404-cellar.jpg",
            import.meta.url,
        ),
    ),
]);

test("the 404 page keeps the Heritage layout and returns visitors home", () => {
    assert.match(template, /^<!DOCTYPE html>/u);
    assert.match(template, /twig:theme:BrandLogo/u);
    assert.match(template, /encore_entry_link_tags\(theme_entry/u);
    assert.match(template, /path\('homepage'\)/u);
    assert.match(template, /viti_theme_asset\('images\/photo-404-cellar\.jpg'\)/u);
    assert.ok(backgroundImage.isFile());
    assert.ok(backgroundImage.size > 0);
    assert.match(template, /name="robots" content="noindex,follow"/u);
    assert.match(template, /class="absolute inset-0 z-0"/u);
    assert.match(template, /class="relative z-10 mx-auto/u);
    assert.doesNotMatch(template, /-z-10/u);
    assert.doesNotMatch(template, /http-equiv="refresh"|window\.location/u);
});

test("the visible copy and metadata exist in both supported locales", () => {
    for (const messages of [frenchMessages, englishMessages]) {
        const notFoundCopy = messages.match(
            /^        not_found:\n(?<content>(?:            .+\n?)+)/mu,
        )?.groups?.content;

        assert.match(messages, /^    error:\n        not_found:/mu);
        assert.match(messages, /^            kicker:/mu);
        assert.match(messages, /^            title:/mu);
        assert.match(messages, /^            text:/mu);
        assert.match(messages, /^            cta:/mu);
        assert.match(messages, /^            logo_link:/mu);
        assert.match(messages, /^            image_alt:/mu);
        assert.ok(notFoundCopy);
        assert.doesNotMatch(notFoundCopy, /Bandock|Bouzy/u);
    }

    for (const meta of [frenchMeta, englishMeta]) {
        const errorMetadata = meta.match(
            /^error404:\n(?<content>(?:    .+\n?)+)/mu,
        )?.groups?.content;

        assert.match(meta, /^error404:\n    title:/mu);
        assert.match(meta, /^    description:/mu);
        assert.ok(errorMetadata);
        assert.doesNotMatch(errorMetadata, /Bandock|Bouzy/u);
    }
});
