// spec: e2e/plans/bugs-1.0.6-set01.plan.md §1

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

const CHILD_NAME = 'AssignTitleChild'

async function createTestChild(request: APIRequestContext, name: string): Promise<string> {
  const pre = await request.get('/api/child/list')
  for (const c of (await pre.json()).children ?? []) {
    if (c.name === name) await request.delete(`/api/child/${c.id}`)
  }
  await request.put('/api/child/add', { data: { name, age: 8 } })
  const list = await request.get('/api/child/list')
  return (await list.json()).children?.find((c: any) => c.name === name)?.id ?? ''
}

test.describe('Assign view heading shows child name', () => {
  let childId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createTestChild(request, CHILD_NAME)
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
  })

  test('"Assign Chores" heading contains child name', async ({ page }) => {
    await page.goto(`/parent/${childId}/assign-chores?name=${CHILD_NAME}`)
    await expect(
      page.getByRole('heading', { name: new RegExp(`Assign Chores.*${CHILD_NAME}`) }),
    ).toBeVisible()
  })

  test('"Assign Rewards" heading contains child name', async ({ page }) => {
    await page.goto(`/parent/${childId}/assign-rewards?name=${CHILD_NAME}`)
    await expect(
      page.getByRole('heading', { name: new RegExp(`Assign Rewards.*${CHILD_NAME}`) }),
    ).toBeVisible()
  })

  test('"Assign Kindness Acts" heading contains child name', async ({ page }) => {
    await page.goto(`/parent/${childId}/assign-kindness?name=${CHILD_NAME}`)
    await expect(
      page.getByRole('heading', { name: new RegExp(`Assign Kindness Acts.*${CHILD_NAME}`) }),
    ).toBeVisible()
  })

  test('"Assign Penalties" heading contains child name', async ({ page }) => {
    await page.goto(`/parent/${childId}/assign-penalties?name=${CHILD_NAME}`)
    await expect(
      page.getByRole('heading', { name: new RegExp(`Assign Penalties.*${CHILD_NAME}`) }),
    ).toBeVisible()
  })
})
