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

// Complete Authentik's identification → password flow on whatever page is
// currently showing it (used both for direct login and mid-OAuth redirect).
// Idempotent: if Authentik already has a session and skipped straight through,
// the fields won't appear and this returns without error.
export async function completeAuthentikLogin(page: Page, user: string, pass: string): Promise<void> {
  const uid = page.locator('input[name="uidField"], input[type="email"], input[type="text"]').first();
  if (await uid.isVisible({ timeout: 8_000 }).catch(() => false)) {
    await uid.fill(user);
    await page.keyboard.press('Enter');
  }

  const pw = page.locator('input[type="password"]').first();
  if (await pw.isVisible({ timeout: 8_000 }).catch(() => false)) {
    await pw.fill(pass);
    await page.keyboard.press('Enter');
  }

  // Authentik may show a consent/authorize step on first SSO to an app.
  const authorize = page.getByRole('button', { name: /authorize|continue|allow/i }).first();
  if (await authorize.isVisible({ timeout: 5_000 }).catch(() => false)) {
    await authorize.click();
  }

  await expect(page.getByText(/invalid|incorrect|failed to/i)).toHaveCount(0);
}
