import { test, expect } from '@playwright/test';
import { TARGETS, url } from '../targets';

const t = TARGETS.find((x) => x.name === 'authentik')!;

// Authentik: the real signal. A healthy pod does NOT prove OIDC/redirect/session
// work — only a completed sign-in does. Credentials come from env (injected from
// the secret store in-cluster), never hardcoded.
const USER = process.env.AK_ADMIN_USER ?? 'akadmin';
const PASS = process.env.AK_ADMIN_PASSWORD;

test('authentik admin can sign in', async ({ page }) => {
  test.skip(!PASS, 'AK_ADMIN_PASSWORD not set — provide via secret to run the login flow');

  await page.goto(url(t), { waitUntil: 'domcontentloaded' });

  // Authentik identification stage: username, Enter/continue, then password.
  const uid = page.locator('input[name="uidField"], input[type="text"], input[type="email"]').first();
  await expect(uid).toBeVisible();
  await uid.fill(USER);
  await page.keyboard.press('Enter');

  const pw = page.locator('input[type="password"]').first();
  await expect(pw).toBeVisible();
  await pw.fill(PASS!);
  await page.keyboard.press('Enter');

  // Landed on the user dashboard — no auth error banner.
  await expect(page).toHaveURL(/\/if\/user|\/if\/admin|\/library/i, { timeout: 20_000 });
  await expect(page.getByText(/invalid|incorrect|failed/i)).toHaveCount(0);
  await page.screenshot({ path: 'test-results/authentik-dashboard.png', fullPage: true });
});
