import { test as base, expect } from '@playwright/test';

/**
 * E2E fixtures for the alerting UI smoke suite.
 *
 * Auth happens once per test via an auto-applied fixture. Override creds via:
 *   E2E_ADMIN_USER=... E2E_ADMIN_PASS=... npm run test:e2e
 *
 * The fixture logs in to the local form (not OIDC). The backend in the
 * Docker-compose stack defaults to `admin` / `admin` for the local login.
 */
export const ADMIN_USER = process.env.E2E_ADMIN_USER ?? 'admin';
export const ADMIN_PASS = process.env.E2E_ADMIN_PASS ?? 'admin';

type Fixtures = {
  loggedIn: void;
};

export const test = base.extend<Fixtures>({
  loggedIn: [
    async ({ page }, use) => {
      // `?local` keeps the login page's auto-OIDC-redirect from firing so the
      // form-based login works even when an OIDC config happens to be present.
      await page.goto('/login?local');
      await page.getByLabel(/username/i).fill(ADMIN_USER);
      await page.getByLabel(/password/i).fill(ADMIN_PASS);
      await page.getByRole('button', { name: /sign in/i }).click();
      // Default landing after login is /exchanges (via Navigate redirect).
      await expect(page).toHaveURL(/\/(exchanges|alerts|dashboard)/, { timeout: 15_000 });
      // Env selection is required for every alerts query (useSelectedEnv gate).
      // Pick the default env so hooks enable.
      await page.getByRole('combobox').selectOption({ label: 'default' });
      await use();
    },
    { auto: true },
  ],
});

export { expect };
