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

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

const CHILD_NAME = 'OverrideSSEChild'
const CHORE_NAME = 'OverrideSSEChore'
const KIND_NAME = 'OverrideSSEKindness'
const PEN_NAME = 'OverrideSSEPenalty'

const CHORE_POINTS = 10
const KIND_POINTS = 15
const PEN_POINTS = 8

async function createChild(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 ?? ''
}

async function createTask(
  request: APIRequestContext,
  name: string,
  type: 'chore' | 'kindness' | 'penalty',
  points: number,
): Promise<string> {
  const pre = await request.get('/api/task/list')
  for (const t of (await pre.json()).tasks ?? []) {
    if (t.name === name) await request.delete(`/api/task/${t.id}`)
  }
  await request.put('/api/task/add', { data: { name, points, type } })
  const list = await request.get('/api/task/list')
  return (await list.json()).tasks?.find((t: any) => t.name === name)?.id ?? ''
}

function choreSection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Chores' }),
  })
}

function kindnessSection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Kindness Acts' }),
  })
}

function penaltySection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Penalties' }),
  })
}

test.describe('Override SSE updates child view', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let choreId = ''
  let kindId = ''
  let penId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    choreId = await createTask(request, CHORE_NAME, 'chore', CHORE_POINTS)
    kindId = await createTask(request, KIND_NAME, 'kindness', KIND_POINTS)
    penId = await createTask(request, PEN_NAME, 'penalty', PEN_POINTS)

    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [choreId], type: 'chore' },
    })
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [kindId], type: 'kindness' },
    })
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [penId], type: 'penalty' },
    })
  })

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

  test('Changing chore override points updates child view in real time', async ({
    page,
    request,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Verify original points displayed
    await expect(card.getByText(`${CHORE_POINTS} Points`)).toBeVisible()

    // Set override via API
    await request.put(`/api/child/${childId}/override`, {
      data: { entity_id: choreId, entity_type: 'task', custom_value: 25 },
    })

    // Without page reload, verify the card updates
    await expect(card.getByText('25 Points')).toBeVisible()
  })

  test('Changing kindness override points updates child view', async ({ page, request }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await card.waitFor({ state: 'visible' })

    await expect(card.getByText(`${KIND_POINTS} Points`)).toBeVisible()

    await request.put(`/api/child/${childId}/override`, {
      data: { entity_id: kindId, entity_type: 'task', custom_value: 30 },
    })

    await expect(card.getByText('30 Points')).toBeVisible()
  })

  test('Changing penalty override points updates child view', async ({ page, request }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await expect(card.getByText(`${PEN_POINTS} Points`)).toBeVisible()

    await request.put(`/api/child/${childId}/override`, {
      data: { entity_id: penId, entity_type: 'task', custom_value: 20 },
    })

    await expect(card.getByText('20 Points')).toBeVisible()
  })

  test('Deleting an override reverts child view to original points', async ({ page, request }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Currently showing overridden value from earlier test
    await expect(card.getByText('25 Points')).toBeVisible()

    // Delete the override
    await request.delete(`/api/child/${childId}/override/${choreId}`)

    // Without page reload, verify the card reverts to original points
    await expect(card.getByText(`${CHORE_POINTS} Points`)).toBeVisible()
  })
})
