import { test as setup } from '@playwright/test'
import {
  STORAGE_STATE_DELETE,
  E2E_DELETE_EMAIL,
  E2E_DELETE_PASSWORD,
  E2E_DELETE_PIN,
} from './e2e-constants'

const BACKEND = 'http://localhost:5000'

setup('authenticate delete user', async ({ page }) => {
  // Create the isolated delete-test user (separate from the main E2E user)
  const createRes = await page.request.post(`${BACKEND}/auth/e2e-create-delete-user`)
  if (!createRes.ok()) {
    throw new Error(
      `e2e-create-delete-user failed: ${createRes.status()} ${await createRes.text()}`,
    )
  }

  await page.goto('/auth/login')
  await page.getByLabel('Email address').fill(E2E_DELETE_EMAIL)
  await page.getByLabel('Password').fill(E2E_DELETE_PASSWORD)
  await page.getByRole('button', { name: 'Sign in' }).click()

  await page.waitForURL(/\/(parent|child)/)

  await page.getByRole('button', { name: 'Parent login' }).click()

  const pinInput = page.getByPlaceholder('4–6 digits')
  await pinInput.waitFor({ timeout: 5000 })
  await pinInput.fill(E2E_DELETE_PIN)
  await page.getByLabel('Stay in parent mode on this device').check()
  await page.getByRole('button', { name: 'OK' }).click()

  await page.waitForURL(/\/parent(\/|$)/)

  try {
    await page.getByRole('button', { name: 'Add Child' }).waitFor({ timeout: 5000 })
  } catch (e) {
    await page.screenshot({ path: 'auth-setup-delete-parent-fail.png' })
    throw new Error(
      'Delete user parent mode not reached after PIN entry. See auth-setup-delete-parent-fail.png for details.',
    )
  }

  await page.context().storageState({ path: STORAGE_STATE_DELETE })
})
