import { expect, test } from '@playwright/test';
import { expectNoA11yViolations } from './support/axe';
import { signIn } from './support/cms';

/**
 * História 10 — Admin surface do Layout (F4.I3.T3, ADR-015/016): a superfície existe **só** no
 * painel (`/cms`), protegida pela permissão `layout.{ver|editar}` (ADR-033). Pré-condição:
 * `php artisan db:seed` (o perfil demo global `*` é semeado).
 */

test.describe('CMS — Layout por grupo de URL', () => {
  test('lista e abre a edição do perfil de layout', async ({ page }) => {
    await signIn(page);

    await page.goto('/layout');
    await expect(
      page.getByRole('heading', { level: 1, name: /Layout por grupo de URL/i }),
    ).toBeVisible();
    await expect(page.getByRole('cell', { name: '*' })).toBeVisible();
    await expectNoA11yViolations(page);

    await page.getByRole('link', { name: 'Editar perfil' }).first().click();
    await expect(page.getByLabel('Grupo de URL')).toHaveValue('*');
    await expectNoA11yViolations(page);
  });

  test('o erro de validação aparece na tela, não só na sessão', async ({ page }) => {
    await signIn(page);

    await page.goto('/layout/criar');

    // `*` já existe (perfil demo) → o escopo duplicado é recusado.
    await page.getByLabel('Grupo de URL').fill('*');
    await page.getByRole('button', { name: 'Salvar' }).click();

    // Dois `role="alert"`: o resumo (#form-errors) e a mensagem do campo — ambos visíveis.
    const summary = page.locator('#form-errors');

    await expect(summary).toBeVisible();
    await expect(summary).toContainText('Já existe um perfil com esse grupo de URL.');
    await expect(page.getByRole('alert')).toHaveCount(2);
    await expect(page.getByLabel('Grupo de URL')).toHaveAttribute('aria-invalid', 'true');
    await expect(page.locator('#field-scope-error')).toHaveText(
      'Já existe um perfil com esse grupo de URL.',
    );

    await expectNoA11yViolations(page);
  });
});
