/**
 * USER_JOURNEYS.md §11 — admin login. Tests the /admin/login route and
 * the redirect-while-already-logged-in shortcut.
 */
import { test, expect } from '../../fixtures/test';
import { AdminLoginPage } from '../../page-objects';
import { ADMIN_PASSWORD } from '../../fixtures/api-client';

test.describe('Auth — admin login', () => {
  test('correct password → /admin dashboard', async ({ page }) => {
    const login = new AdminLoginPage(page);
    await login.goto();
    await login.login(ADMIN_PASSWORD);
    await page.waitForURL('**/admin', { timeout: 10_000 });

    // The admin JWT lands in sessionStorage (USER_JOURNEYS §11.1) — NOT localStorage — so the
    // elevated credential doesn't survive a tab/browser close on a shared "event laptop".
    const stores = await page.evaluate(() => {
      const decodeRole = (t: string | null) => {
        if (!t) return null;
        try {
          return JSON.parse(atob(t.split('.')[1])).role;
        } catch {
          return null;
        }
      };
      return {
        sessionRole: decodeRole(sessionStorage.getItem('eventsnap_jwt')),
        localToken: localStorage.getItem('eventsnap_jwt'),
      };
    });
    expect(stores.sessionRole).toBe('admin');
    expect(stores.localToken, 'admin token must not persist in localStorage').toBeNull();
  });

  test('wrong password → error, no token written', async ({ page }) => {
    const login = new AdminLoginPage(page);
    await login.goto();
    await login.login('definitely-not-the-password');
    await expect(login.errorMessage).toContainText(/falsch|forbidden|password/i);
    const token = await page.evaluate(() => localStorage.getItem('eventsnap_jwt'));
    expect(token).toBeNull();
  });

  test('already logged in as admin → auto-redirect to /admin', async ({ page, api }) => {
    const adminJwt = await api.adminLogin();
    await page.goto('/');
    await page.evaluate((jwt) => localStorage.setItem('eventsnap_jwt', jwt), adminJwt);
    await page.goto('/admin/login');
    await page.waitForURL('**/admin', { timeout: 5_000 });
  });
});
