/**
 * A-series: Auth flows — login, logout, route protection, role visibility.
 *
 * Uses live Keycloak login per test (see fixtures/login.ts). The passthrough
 * lock in `$lib/supabase` is required for queries to resolve in headless
 * Chromium — see the comment there for details.
 */
import { test, expect } from '@playwright/test';
import { USERS, COLLECTIVE_NAME, KEYCLOAK_REALM } from '../fixtures/users.js';
import { loginAs } from '../fixtures/login.js';

test.describe('Auth — login and route protection', () => {
	test('A-01: unauthenticated user is redirected to Keycloak', async ({ page }) => {
		await page.goto('/lists');
		await expect(page).toHaveURL(
			new RegExp(`realms/${KEYCLOAK_REALM}/protocol/openid-connect/auth`),
			{ timeout: 10_000 }
		);
	});

	test('A-02: Ana can log in and reach the app', async ({ page }) => {
		await loginAs(page, USERS.ana);
		await expect(page.locator('body')).not.toContainText('Error');
	});

	test('A-04: Ana sees the collective name in the sidebar', async ({ page }) => {
		await loginAs(page, USERS.ana);
		await page.goto('/lists');
		// Sidebar button label includes both the emoji and the collective name
		await expect(
			page.getByRole('button', { name: new RegExp(COLLECTIVE_NAME) })
		).toBeVisible({ timeout: 15_000 });
	});

	test('A-05: Ana can sign out', async ({ page }) => {
		await loginAs(page, USERS.ana);
		await page.goto('/settings');

		const signOutButton = page.getByRole('button', { name: /sign out|cerrar sesión/i });
		await expect(signOutButton).toBeVisible({ timeout: 10_000 });
		await signOutButton.click();

		// After sign out, the session is cleared. The (app) layout's auth effect
		// will redirect back to Keycloak for re-auth (SSO still active there), so
		// we end up somewhere other than /settings. We just verify we left.
		await expect(page).not.toHaveURL(/\/settings/, { timeout: 15_000 });
	});

	test('A-06: David (guest) can log in and see the collective', async ({ page }) => {
		await loginAs(page, USERS.david);
		await page.goto('/lists');
		await expect(
			page.getByRole('button', { name: new RegExp(COLLECTIVE_NAME) })
		).toBeVisible({ timeout: 15_000 });
	});
});
