/**
 * Playwright global setup — runs once before all test files.
 *
 * Responsibilities:
 * 1. Wait for the backend health endpoint to respond (the webServer config
 *    already polls the URL, but we double-check here for robustness).
 * 2. Invoke the Python script that creates / updates the E2E test admin user
 *    in the auth SQLite DB.
 */

import { execFileSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const BACKEND_HEALTH_URL = 'http://127.0.0.1:8000/api/v1/health'
const SETUP_SCRIPT = resolve(__dirname, 'setup-test-user.py')

/** Poll a URL until it returns 200 or the timeout expires. */
async function waitForUrl(url: string, timeoutMs = 60_000): Promise<void> {
  const deadline = Date.now() + timeoutMs
  while (Date.now() < deadline) {
    try {
      const resp = await fetch(url)
      if (resp.ok) return
    } catch {
      // server not ready yet
    }
    await new Promise((r) => setTimeout(r, 1000))
  }
  throw new Error(`Timed out waiting for ${url}`)
}

export default async function globalSetup(): Promise<void> {
  // 1. Verify backend is up (webServer should have started it already).
  await waitForUrl(BACKEND_HEALTH_URL, 60_000)
  console.log('[global-setup] Backend health check passed')

  // 2. Create / update the test admin user.
  if (!existsSync(SETUP_SCRIPT)) {
    throw new Error(`Setup script not found: ${SETUP_SCRIPT}`)
  }

  const pythonBin = process.env.E2E_PYTHON ?? 'python3'
  try {
    execFileSync(pythonBin, [SETUP_SCRIPT], {
      stdio: 'inherit',
      timeout: 30_000,
    })
  } catch (err) {
    throw new Error(
      `Failed to create test user via ${pythonBin} ${SETUP_SCRIPT}: ${
        err instanceof Error ? err.message : String(err)
      }`
    )
  }
  console.log('[global-setup] Test user ready')
}
