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

// AZ-467 — e2e variants of the RBAC scenarios that require the real
// admin/ service to issue role-specific bearers and the suite's nginx to
// route /admin and /settings.
//
//   FT-N-03 — Operator → /admin redirects to /flights (or to /login if
//             permission middleware is unauthenticated-equivalent)
//   FT-N-05 — integrator-dave → /settings redirects (no SETTINGS perm)
//
// Profile: e2e (gated by docker compose). Skipped in fast/host runs.
//
// Production status: src/auth/ProtectedRoute.tsx does NOT check
// permissions today (only `user != null`). These tests are wrapped in
// `test.fail()` to capture the drift — they will start passing once
// ProtectedRoute gains a `requirePermission` prop (or wrapping) and the
// /admin and /settings routes opt in.

const OPERATOR_EMAIL = 'op_bob@test.local'        // Operator without ADMIN_WRITE / SETTINGS
const INTEGRATOR_EMAIL = 'integrator_dave@test.local' // SystemIntegrator without SETTINGS
const ADMIN_EMAIL = 'admin_carol@test.local'      // Admin with full perms
const TEST_PASSWORD = 'TestPassword!23'

async function login(page: import('@playwright/test').Page, email: string) {
  await page.goto('/login')
  await page.getByLabel(/email/i).fill(email)
  await page.getByLabel(/password/i).fill(TEST_PASSWORD)
  await Promise.all([
    page.waitForResponse(
      (r) => r.url().includes('/api/admin/auth/login') && r.request().method() === 'POST',
    ),
    page.getByRole('button', { name: /sign in/i }).click(),
  ])
}

test.describe('AZ-467 e2e — RBAC route gating', () => {
  test('FT-N-03 — Operator hitting /admin is redirected to /flights (AC-3 drift)', async ({ page }) => {
    test.fail(
      true,
      'AC-3 drift: src/auth/ProtectedRoute.tsx today checks only `user != null`. Test passes once route-level RBAC lands.',
    )
    await login(page, OPERATOR_EMAIL)
    await page.goto('/admin')
    await expect(page).toHaveURL(/\/flights$/)
  })

  test('FT-N-05 — integrator-dave hitting /settings is redirected away (AC-3 drift)', async ({ page }) => {
    test.fail(
      true,
      'AC-3 drift: same as FT-N-03 — ProtectedRoute does not gate on permissions today.',
    )
    await login(page, INTEGRATOR_EMAIL)
    await page.goto('/settings')
    await expect(page).not.toHaveURL(/\/settings$/)
  })

  test('Admin reaches /admin normally (positive control)', async ({ page }) => {
    await login(page, ADMIN_EMAIL)
    await page.goto('/admin')
    await expect(page).toHaveURL(/\/admin$/)
  })
})
