/**
 * Étape 5 : VérifActe. L'API est simulée (https://api.e2e.example, voir src/lib/donnees.ts) avec
 * les attestations fictives de @notariat-ci/verifacte : aucun appel à une vraie base.
 */
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
import { ATTESTATIONS_FICTIVES, reponseFictive } from '@notariat-ci/verifacte/fictif';

const KO = 1024;
const [VALIDE, , REVOQUEE] = ATTESTATIONS_FICTIVES;
if (!VALIDE || !REVOQUEE) throw new Error('attestations fictives manquantes');

/** Simule public.verifier_attestation ; renvoie la liste des codes demandés. */
async function simulerApi(page: Page, statut = 200) {
  const demandes: string[] = [];
  await page.route('https://api.e2e.example/rest/v1/rpc/verifier_attestation', async (route) => {
    const { code } = route.request().postDataJSON() as { code: string };
    demandes.push(code);
    const attestation = ATTESTATIONS_FICTIVES.find((a) => a.code === code);
    await route.fulfill({
      status: statut,
      contentType: 'application/json',
      body: JSON.stringify(statut === 200 && attestation ? [reponseFictive(attestation)] : []),
    });
  });
  return demandes;
}

async function ouvrir(page: Page, chemin: string) {
  await page.goto(chemin);
  await page.waitForFunction(() => !document.querySelector('astro-island[ssr]'));
}

async function violationsAxe(page: Page) {
  const r = await new AxeBuilder({ page })
    .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
    .analyze();
  return r.violations.map((v) => ({ regle: v.id, elements: v.nodes.map((n) => n.target) }));
}

const fichier = (contenu: string) => ({
  name: 'acte.pdf',
  mimeType: 'application/pdf',
  buffer: Buffer.from(contenu, 'utf8'),
});

test.describe('VérifActe', () => {
  for (const chemin of ['/verifier', '/en/verifier']) {
    for (const preference of ['light', 'dark'] as const) {
      test(`${chemin} (${preference}) : aucune violation axe, résultat et comparaison affichés`, async ({
        page,
      }) => {
        await page.emulateMedia({ colorScheme: preference });
        await simulerApi(page);
        await ouvrir(page, `${chemin}?code=${VALIDE.code}`);
        await expect(page.locator('[data-resultat="valide"]').first()).toBeVisible();
        await page.locator('input[type=file]').setInputFiles(fichier(VALIDE.document));
        await expect(page.locator('[data-resultat]')).toHaveCount(2);
        expect(await violationsAxe(page)).toEqual([]);
      });
    }
  }

  test('le QR mène à une attestation valide : notaire, sceau, empreinte', async ({ page }) => {
    const demandes = await simulerApi(page);
    await ouvrir(page, `/verifier?code=${VALIDE.code}`);
    await expect(
      page.getByRole('heading', { name: 'Attestation valide : cet acte est enregistré.' }),
    ).toBeVisible();
    await expect(page.getByRole('link', { name: 'Maître Aminata Koné' })).toHaveAttribute(
      'href',
      '/annuaire/kone-aminata',
    );
    await expect(page.getByText(VALIDE.empreinte)).toBeVisible();
    const sceau = page.getByRole('img', { name: `Sceau de l'acte ${VALIDE.code}` });
    await expect(sceau).toBeVisible();
    expect(await sceau.evaluate((img: HTMLImageElement) => img.naturalWidth > 0)).toBe(true);
    expect(demandes).toEqual([VALIDE.code]);
  });

  test('le fichier est comparé sur l’appareil, sans être envoyé', async ({ page }) => {
    await simulerApi(page);
    const envois: string[] = [];
    page.on('request', (r) => {
      if (r.method() !== 'GET') envois.push(r.postData() ?? '');
    });
    await ouvrir(page, `/verifier?code=${VALIDE.code}`);
    const champ = page.getByLabel("Fichier de l'acte");

    await champ.setInputFiles(fichier(VALIDE.document));
    await expect(
      page.getByRole('heading', { name: /^Identique : ce document est bien celui/ }),
    ).toBeVisible();

    await champ.setInputFiles(fichier(`${VALIDE.document} `));
    await expect(
      page.getByRole('heading', { name: /^Différent : ce document n'est pas/ }),
    ).toBeVisible();

    // Seule la question « ce code existe-t-il ? » est partie : jamais le contenu du fichier.
    expect(envois).toEqual([JSON.stringify({ code: VALIDE.code })]);
  });

  test('attestation révoquée : mise en garde', async ({ page }) => {
    await simulerApi(page);
    await ouvrir(page, `/verifier?code=${REVOQUEE.code}`);
    await expect(page.locator('[data-resultat="revoque"]').getByRole('heading')).toHaveText(
      /^Attestation révoquée le 22 novembre 2026/,
    );
  });

  test('saisie tolérante : minuscules, espaces, lettre O ; l’adresse est mise à jour', async ({
    page,
  }) => {
    const demandes = await simulerApi(page);
    await ouvrir(page, '/verifier');
    await page.getByLabel('Code de vérification').fill(' dem0a 0OOO1 ');
    await page.getByRole('button', { name: 'Vérifier' }).click();
    await expect(page.locator('[data-resultat="valide"]')).toBeVisible();
    expect(demandes).toEqual(['DEM0A-00001']);
    await expect(page).toHaveURL(/\/verifier\?code=DEM0A-00001$/);
  });

  test('code inconnu, code mal formé, panne du service', async ({ page }) => {
    const demandes = await simulerApi(page);
    await ouvrir(page, '/verifier?code=ZZZZZ-99999');
    await expect(
      page.getByRole('heading', { name: "Aucun acte n'est enregistré sous ce code." }),
    ).toBeVisible();

    const champ = page.getByLabel('Code de vérification');
    await champ.fill('ABC');
    await page.getByRole('button', { name: 'Vérifier' }).click();
    await expect(champ).toHaveAttribute('aria-invalid', 'true');
    expect(demandes).toEqual(['ZZZZZ-99999']);

    await page.unrouteAll();
    await simulerApi(page, 503);
    await champ.fill('ABCDE-12345');
    await page.getByRole('button', { name: 'Vérifier' }).click();
    await expect(page.getByRole('alert')).toHaveText(/La vérification n'a pas abouti/);
  });

  test('sans JavaScript : la démarche et une alternative sont données', async ({ browser }) => {
    const contexte = await browser.newContext({ javaScriptEnabled: false });
    const page = await contexte.newPage();
    await page.goto(`/verifier?code=${VALIDE.code}`);
    await expect(page.getByText(/nécessite JavaScript/)).toBeVisible();
    await expect(page.getByRole('heading', { name: 'Comment faire ?' })).toBeVisible();
    await contexte.close();
  });

  test('la page transfère moins de 300 Ko', async ({ page }) => {
    await simulerApi(page);
    const mesures: Promise<number>[] = [];
    page.on('requestfinished', (requete) => {
      mesures.push(requete.sizes().then((t) => t.responseBodySize + t.responseHeadersSize));
    });
    await page.goto(`/verifier?code=${VALIDE.code}`, { waitUntil: 'networkidle' });
    const total = (await Promise.all(mesures)).reduce((s, n) => s + n, 0);
    expect(total, `${(total / KO).toFixed(1)} Ko`).toBeLessThan(300 * KO);
  });
});
