/**
 * Admin portal — happy path.
 *
 * Logs the seeded admin in, verifies the stats dashboard renders, and walks
 * to the doctor verification queue + audit log + AI settings page. We assert
 * the page-level heading on each landing so any 500 from /api/admin/* fails
 * the spec early.
 */
import { test, expect, type Page } from '@playwright/test';
import { PORTALS, USERS } from '../../fixtures/users';

async function login(page: Page) {
  await page.goto(`${PORTALS.admin}/login`);
  await page.getByRole('textbox', { name: 'Email' }).fill(USERS.admin.email);
  await page.getByRole('textbox', { name: 'Password' }).fill(USERS.admin.password);
  await page.getByRole('button', { name: /sign in/i }).click();
  await page.waitForURL(/\/dashboard$/, { timeout: 15_000 });
}

test.describe.serial('Admin happy path', () => {
  test('1) dashboard greets the admin by name', async ({ page }) => {
    await login(page);
    await expect(page.getByRole('heading', { level: 1 })).toContainText(/Asma/i);
    await expect(page.getByRole('heading', { name: /admin actions/i })).toBeVisible();
  });

  test('2) doctors verification page lists the seeded approved doctor', async ({ page }) => {
    await login(page);
    await page.goto(`${PORTALS.admin}/doctors`);
    await expect(page.getByRole('heading', { name: /doctor verification/i })).toBeVisible();
    // Seed inserts Dr. Imran Rashid as approved. Default filter may be
    // "Pending" — switch to "Approved" so we can assert on him.
    await page.getByRole('button', { name: /^approved$/i }).first().click().catch(() => {
      // Filter UI may use anchor tabs instead of buttons; ignore if absent.
    });
    await expect(page.getByText(/Imran Rashid/i).first()).toBeVisible({ timeout: 15_000 });
  });

  test('3) audit logs page renders without 500', async ({ page }) => {
    await login(page);
    await page.goto(`${PORTALS.admin}/audit-logs`);
    await expect(page.getByRole('heading').first()).toBeVisible();
    // Login events are audit-logged — so we expect at least one row referencing
    // the admin's email or a known action. Soft-asserted: the API may rate-cap.
    const auditTable = page.locator('table, [role="table"]');
    if (await auditTable.count()) {
      await expect(auditTable.first()).toBeVisible();
    }
  });

  test('4) AI settings page renders the config form', async ({ page }) => {
    await login(page);
    await page.goto(`${PORTALS.admin}/settings/ai`);
    await expect(page.getByRole('heading').first()).toBeVisible();
  });

  test('5) logout clears the admin session', async ({ page }) => {
    await login(page);
    await page.goto(`${PORTALS.admin}/dashboard`);
    await page.getByRole('button', { name: /sign out|log ?out/i }).click();
    await page.waitForURL(/\/login/, { timeout: 10_000 });
  });
});
