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

// These tests use a fresh browser context (no saved auth state)
test.use({ storageState: { cookies: [], origins: [] } });

test.describe("Authentication flow", () => {
  test("unauthenticated visit to /dashboard redirects to Keycloak", async ({
    page,
  }) => {
    await page.goto("/dashboard");

    // Should end up on Keycloak login page
    await page.waitForSelector("#username", { timeout: 15_000 });
    await expect(page.locator("#kc-login")).toBeVisible();
  });

  test("valid credentials log in and redirect to dashboard", async ({
    page,
  }) => {
    await page.goto("/dashboard");
    await page.waitForSelector("#username", { timeout: 15_000 });

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

    await page.waitForURL("**/dashboard", { timeout: 15_000 });
    await expect(page.locator(".dashboard-page")).toBeVisible();
  });

  test("dashboard shows sidebar with user info after login", async ({
    page,
  }) => {
    await page.goto("/dashboard");
    await page.waitForSelector("#username", { timeout: 15_000 });

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

    await page.waitForURL("**/dashboard", { timeout: 15_000 });
    await expect(page.locator(".sidebar-name")).toBeVisible();
    await expect(page.locator(".sidebar-email")).toBeVisible();
  });

  test("logout redirects away from dashboard", async ({ page }) => {
    // First log in
    await page.goto("/dashboard");
    await page.waitForSelector("#username", { timeout: 15_000 });

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

    await page.waitForURL("**/dashboard", { timeout: 15_000 });

    // Click logout
    await page.locator('a.logout-btn, a[href="/logout"]').click();

    // Should no longer be on the dashboard
    await expect(page).not.toHaveURL(/\/dashboard/);
  });
});
