/**
 * 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 });
	});

	// Helper: click through Keycloak's "Do you want to log out?" confirmation.
	// Keycloak shows this whenever the end-session request is made without
	// `id_token_hint` — which is our case, because GoTrue's proxy flow does
	// not expose the Keycloak id_token to the client. In prod users see it
	// as a one-click confirmation, which is acceptable.
	async function confirmKeycloakLogout(page: import('@playwright/test').Page) {
		await page.waitForURL(/realms\/colectivo\/protocol\/openid-connect\/logout/, {
			timeout: 15_000
		});
		await page.getByRole('button', { name: /^logout$/i }).click();
	}

	test('A-05: Ana can sign out (ends Keycloak SSO, lands on /logged-out)', async ({ page }) => {
		const pkceErrors: string[] = [];
		page.on('console', (msg) => {
			const t = msg.text();
			if (/PKCE code verifier not found/i.test(t)) pkceErrors.push(t);
		});

		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();

		await confirmKeycloakLogout(page);

		// After the Keycloak confirmation, browser lands on /logged-out.
		await page.waitForURL(/\/logged-out(\?|$|#)/, { timeout: 20_000 });

		// No Supabase session should remain.
		const hasSession = await page.evaluate(() =>
			Object.keys(localStorage).some(
				(k) => k.startsWith('sb-') && k.endsWith('-auth-token') && !!localStorage.getItem(k)
			)
		);
		expect(hasSession).toBe(false);

		// And no PKCE error was emitted during the flow.
		expect(pkceErrors).toEqual([]);
	});

	test('A-07: after sign out, next login prompts for Keycloak credentials', async ({ page }) => {
		await loginAs(page, USERS.ana);
		await page.goto('/settings');
		await page.getByRole('button', { name: /sign out|cerrar sesión/i }).click();
		await confirmKeycloakLogout(page);
		await page.waitForURL(/\/logged-out/, { timeout: 20_000 });

		// Navigate anywhere in the (app) group — the auth effect should push us
		// to Keycloak, and because the SSO cookie was cleared by RP-initiated
		// logout, Keycloak must render the login form (not silently redirect).
		await page.goto('/lists');
		await page.waitForURL(
			new RegExp(`realms/${KEYCLOAK_REALM}/protocol/openid-connect/auth`),
			{ timeout: 15_000 }
		);
		await expect(page.locator('#username')).toBeVisible({ timeout: 10_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 });
	});
});
