import { test as setup, expect } from "@playwright/test";
import path from "node:path";

/**
 * Auth-Setup (Plan WS11 Aufgabe 3): echter Credentials-Login je Konto ->
 * storageState. Wird als Playwright-Projekt "setup" ausgeführt; die übrigen
 * Projekte hängen davon ab und laden den jeweiligen storageState.
 *
 * NICHT in der Sandbox ausführbar (kein Server/DB) — deferred.
 *
 * Erzeugt vier Storage-States passend zu den vier Seed-Konten:
 *  - platform_admin
 *  - wehr_admin (Wehr A)
 *  - wehr_admin (Wehr B)
 *  - wehr_read  (Wehr A)
 */
export const AUTH_DIR = path.join(process.cwd(), "tests/e2e/.auth");

interface Account {
  email: string;
  file: string;
  envVar: string;
}

const PASSWORD = process.env.E2E_TEST_PASSWORD ?? "Test-Passwort-1234";

const ACCOUNTS: Account[] = [
  {
    email: "platform-admin@example.test",
    file: "platform-admin.json",
    envVar: "E2E_PLATFORM_ADMIN_STATE",
  },
  {
    email: "wehr-admin-a@example.test",
    file: "wehr-admin-a.json",
    envVar: "E2E_WEHR_ADMIN_STATE",
  },
  {
    email: "wehr-admin-b@example.test",
    file: "wehr-admin-b.json",
    envVar: "E2E_WEHR_ADMIN_B_STATE",
  },
  {
    email: "wehr-read-a@example.test",
    file: "wehr-read-a.json",
    envVar: "E2E_WEHR_READ_STATE",
  },
];

for (const account of ACCOUNTS) {
  setup(`Login ${account.email}`, async ({ page }) => {
    await page.goto("/login");
    await page.getByLabel(/E-Mail/i).fill(account.email);
    await page.getByLabel(/Passwort/i).fill(PASSWORD);
    await page.getByRole("button", { name: /Anmelden/i }).click();
    // Erfolgreicher Login verlässt /login.
    await page.waitForURL((url) => !url.pathname.startsWith("/login"));
    await expect(page).not.toHaveURL(/\/login/);
    await page
      .context()
      .storageState({ path: path.join(AUTH_DIR, account.file) });
  });
}
