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

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

const CHILD_NAME = 'ChoreNotifApproveChild'
const CHORE_NAME = 'ChoreNotifApproveChore'
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 — Appearance and In-App Approval', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let choreId = ''
  let pointsBeforeApproval = 0

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

    // Confirm the chore to create a pending notification
    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}`)
  })

  // 2.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 })
    await expect(item).toContainText('completed')
  })

  // 2.2 Notification item displays the child's name
  test('Notification item displays the child name', async ({ page }) => {
    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: CHORE_NAME })
    await expect(item).toBeVisible({ timeout: 5000 })
    await expect(item).toContainText(CHILD_NAME)
  })

  // 2.3 Clicking notification navigates to ParentView with correct query params
  test('Clicking notification navigates to ParentView with correct query params', async ({
    page,
  }) => {
    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: CHORE_NAME })
    await expect(item).toBeVisible({ timeout: 5000 })
    await item.click()
    await page.waitForURL(new RegExp(`/parent/${childId}\\?scrollTo=.*&entityType=chore`), {
      timeout: 5000,
    })
    expect(page.url()).toContain(`scrollTo=${choreId}`)
    expect(page.url()).toContain('entityType=chore')
    await expect(page.locator('h3', { hasText: 'Chores' })).toBeVisible()
  })

  // 2.4 Pending chore card shows PENDING stamp in ParentView
  test('Pending chore card shows PENDING stamp in ParentView', 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 expect(card).toContainText('PENDING')
  })

  // 2.5 Clicking a pending chore card opens ChoreApproveDialog
  test('Clicking a pending chore card opens ChoreApproveDialog', 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()
  })

  // 2.6 Approving via ChoreApproveDialog removes the PENDING stamp
  test('Approving 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 })
    // Capture points before approval for test 2.8 verification
    pointsBeforeApproval = await getPoints(page)
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()
    const approveBtn = page.getByRole('button', { name: 'Approve' })
    await expect(approveBtn).toBeVisible({ timeout: 5000 })
    await approveBtn.click()
    await expect(approveBtn).not.toBeVisible({ timeout: 5000 })
    await expect(card).not.toContainText('PENDING', { timeout: 5000 })
  })

  // 2.7 Approving a chore clears it from the notification view
  test('Approving 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 })
  })

  // 2.8 Approving a chore awards points to the child
  test('Approving a chore awards points to the child', async ({ page }) => {
    // The chore was approved in test 2.6. Verify the points were updated correctly.
    // (Cannot re-confirm as the chore was already approved today.)
    await page.goto(`/parent/${childId}`)
    const currentPoints = await getPoints(page)
    expect(currentPoints).toBe(pointsBeforeApproval + CHORE_POINTS)
  })
})
