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

const AUTH_FILE = "e2e/.auth/user.json";

setup("authenticate via Keycloak", async ({ page }) => {
  // Navigate to a protected route to trigger the auth redirect chain:
  // /dashboard -> /auth (Axum) -> Keycloak login page
  await page.goto("/dashboard");

  // Wait for Keycloak login form to appear
  await page.waitForSelector("#username", { timeout: 15_000 });

  // Fill Keycloak credentials
  await page.fill("#username", process.env.TEST_USER ?? "admin@certifai.local");
  await page.fill("#password", process.env.TEST_PASSWORD ?? "admin");
  await page.click("#kc-login");

  // Wait for redirect back to the app dashboard
  await page.waitForURL("**/dashboard", { timeout: 15_000 });
  await expect(page.locator(".sidebar")).toBeVisible();

  // Persist authenticated state (cookies + localStorage)
  await page.context().storageState({ path: AUTH_FILE });
});
