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

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

const CHILD_NAME = 'GeneralChoreChild'
const GENERAL_CHORE_NAME = 'GeneralTestChore'
const SCHEDULED_CHORE_NAME = 'ScheduledTestChore'
const CHORE_POINTS = 10

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,
  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: 'chore' } })
  const list = await request.get('/api/task/list')
  return (await list.json()).tasks?.find((t: any) => t.name === name)?.id ?? ''
}

async function getPoints(page: Page): Promise<number> {
  const text = await page.locator('.points .value').textContent()
  return parseInt(text?.trim() ?? '0', 10)
}

async function activateItem(itemCard: Locator): Promise<void> {
  await itemCard.click()
  await expect(itemCard).toHaveClass(/item-ready/, { timeout: 3000 })
  await itemCard.click()
}

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

test.describe('General chore — no COMPLETED stamp', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let generalChoreId = ''
  let scheduledChoreId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    generalChoreId = await createTask(request, GENERAL_CHORE_NAME, CHORE_POINTS)
    scheduledChoreId = await createTask(request, SCHEDULED_CHORE_NAME, CHORE_POINTS)

    // Assign both chores
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [generalChoreId, scheduledChoreId], type: 'chore' },
    })

    // Only the second chore gets a schedule
    await request.put(`/api/child/${childId}/task/${scheduledChoreId}/schedule`, {
      data: {
        mode: 'interval',
        interval_days: 1,
        anchor_date: new Date().toLocaleDateString('en-CA'),
        interval_has_deadline: false,
      },
    })
  })

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

  test('Approving a general chore awards points', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: GENERAL_CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    const before = await getPoints(page)

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    await expect(page.locator('.points .value')).toHaveText(String(before + CHORE_POINTS))
  })

  test('General chore does NOT show COMPLETED stamp after approval', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: GENERAL_CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    await expect(card.getByText('COMPLETED')).not.toBeVisible()
  })

  test('General chore can be triggered again immediately after approval', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: GENERAL_CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Scheduled chore DOES show COMPLETED after approval', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: SCHEDULED_CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    await expect(card.getByText('COMPLETED')).toBeVisible()
  })
})
