// spec: e2e/plans/parent-notifications.plan.md §3

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

const CHILD_NAME = 'ChoreNotifDenyChild'
const CHORE_NAME = 'ChoreNotifDenyChore'
const CHORE_POINTS = 5

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)
}

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

test.describe('Chore Notification — In-App Rejection', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let choreId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    choreId = await createTask(request, CHORE_NAME, CHORE_POINTS)

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

    // Set a daily interval schedule so the chore persists post-rejection
    await request.put(`/api/child/${childId}/task/${choreId}/schedule`, {
      data: {
        mode: 'interval',
        interval_days: 1,
        anchor_date: new Date().toLocaleDateString('en-CA'),
        interval_has_deadline: false,
      },
    })

    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: choreId },
    })
  })

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

  // 3.1 Confirmed chore appears in the notification view
  test('Confirmed chore appears in notification view', async ({ page }) => {
    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: CHORE_NAME })
    await expect(item).toBeVisible({ timeout: 5000 })
  })

  // 3.2 ChoreApproveDialog shows both Approve and Reject buttons
  test('ChoreApproveDialog shows both Approve and Reject buttons', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()
    await expect(page.getByRole('button', { name: 'Approve' })).toBeVisible({ timeout: 5000 })
    await expect(page.getByRole('button', { name: 'Reject' })).toBeVisible()
  })

  // 3.3 Rejecting via ChoreApproveDialog removes the PENDING stamp
  test('Rejecting via ChoreApproveDialog removes PENDING stamp', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()
    const rejectBtn = page.getByRole('button', { name: 'Reject' })
    await expect(rejectBtn).toBeVisible({ timeout: 5000 })
    await rejectBtn.click()
    await expect(rejectBtn).not.toBeVisible({ timeout: 5000 })
    await expect(card).not.toContainText('PENDING', { timeout: 5000 })
  })

  // 3.4 Rejecting a chore clears it from the notification view
  test('Rejecting a chore clears it from notification view', async ({ page }) => {
    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: CHORE_NAME })
    await expect(item).not.toBeVisible({ timeout: 5000 })
  })

  // 3.5 Rejecting a chore does not award points
  test('Rejecting a chore does not award points', async ({ page, request }) => {
    // Re-confirm the chore for this test
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: choreId },
    })

    await page.goto(`/parent/${childId}`)
    const before = await getPoints(page)

    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()
    const rejectBtn = page.getByRole('button', { name: 'Reject' })
    await expect(rejectBtn).toBeVisible({ timeout: 5000 })
    await rejectBtn.click()
    await expect(rejectBtn).not.toBeVisible({ timeout: 5000 })

    await expect(page.locator('.points .value')).toHaveText(String(before), { timeout: 5000 })
  })
})
