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

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

const CHILD_NAME = 'PendingResetChild'
const CHORE_NAME = 'PendingResetChore'
const REWARD_NAME = 'PendingResetReward'
const CHORE_POINTS = 10
const REWARD_COST = 20
const INITIAL_CHILD_POINTS = 50

async function createChild(
  request: APIRequestContext,
  name: string,
  points: number,
): 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')
  const id = (await list.json()).children?.find((c: any) => c.name === name)?.id ?? ''
  if (points > 0) await request.put(`/api/child/${id}/edit`, { data: { points } })
  return 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 createReward(
  request: APIRequestContext,
  name: string,
  cost: number,
): Promise<string> {
  const pre = await request.get('/api/reward/list')
  for (const r of (await pre.json()).rewards ?? []) {
    if (r.name === name) await request.delete(`/api/reward/${r.id}`)
  }
  await request.put('/api/reward/add', {
    data: { name, description: 'E2E pending-reset test', cost },
  })
  const list = await request.get('/api/reward/list')
  return (await list.json()).rewards?.find((r: any) => r.name === name)?.id ?? ''
}

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

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

test.describe('Pending status resets on task/reward modification', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let choreId = ''
  let rewardId = ''

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

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

    // Create interval schedule for chore (no deadline)
    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,
      },
    })
  })

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

  test('10.1 Editing chore points clears pending status', async ({ page, request }) => {
    // Create pending via child confirm-chore API
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: choreId },
    })

    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Verify PENDING stamp is visible
    const stamp = card.locator('.chore-stamp')
    await expect(stamp).toHaveText('PENDING')

    // Edit the parent task's points via API (triggers SSE → clears pending)
    await request.put(`/api/task/${choreId}/edit`, { data: { points: CHORE_POINTS + 1 } })

    // Wait for SSE to propagate — PENDING should disappear
    await expect(stamp).not.toBeVisible({ timeout: 5000 })
  })

  test('10.2 Changing chore schedule clears pending status', async ({ page, request }) => {
    // Create pending again (10.1 cleared the previous one)
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: choreId },
    })

    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    const stamp = card.locator('.chore-stamp')
    await expect(stamp).toHaveText('PENDING')

    // Change the schedule via API (triggers SSE → clears pending)
    await request.put(`/api/child/${childId}/task/${choreId}/schedule`, {
      data: {
        mode: 'interval',
        interval_days: 2,
        anchor_date: new Date().toLocaleDateString('en-CA'),
        interval_has_deadline: false,
      },
    })

    await expect(stamp).not.toBeVisible({ timeout: 5000 })
  })

  test('10.5 Editing task name only does NOT clear pending', async ({ page, request }) => {
    // Create pending again
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: choreId },
    })

    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    const stamp = card.locator('.chore-stamp')
    await expect(stamp).toHaveText('PENDING')

    // Edit name only (no points/type change) — should NOT clear pending
    await request.put(`/api/task/${choreId}/edit`, { data: { name: CHORE_NAME } })

    // Wait briefly for SSE to propagate, then verify PENDING is still there
    await page.waitForTimeout(2000)
    await expect(stamp).toHaveText('PENDING')

    // Clean up: cancel the pending confirmation for subsequent tests
    await request.post(`/api/child/${childId}/cancel-confirm-chore`, {
      data: { task_id: choreId },
    })
  })

  test('10.4 Completed chores remain completed after point edit', async ({ page, request }) => {
    // Directly trigger-task (parent approval) → creates approved confirmation for scheduled chore
    await request.post(`/api/child/${childId}/trigger-task`, {
      data: { task_id: choreId },
    })

    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Verify COMPLETED is visible
    await expect(card.getByText('COMPLETED')).toBeVisible()

    // Edit points — only status='pending' is cleared, not approved
    await request.put(`/api/task/${choreId}/edit`, { data: { points: CHORE_POINTS + 2 } })

    // Wait for SSE, then verify COMPLETED stamp is still visible
    await page.waitForTimeout(2000)
    await expect(card.getByText('COMPLETED')).toBeVisible()
  })

  test('10.3 Editing reward cost clears pending reward request', async ({ page, request }) => {
    await page.goto(`/parent/${childId}`)
    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await card.waitFor({ state: 'visible' })

    // Create pending reward request via API
    await request.post(`/api/child/${childId}/request-reward`, {
      data: { reward_id: rewardId },
    })

    // Wait for SSE → PENDING on reward (use .pending class to avoid matching reward name)
    const pendingBadge = card.locator('.pending')
    await expect(pendingBadge).toBeVisible({ timeout: 5000 })

    // Edit reward cost via API → clears pending
    await request.put(`/api/reward/${rewardId}/edit`, { data: { cost: REWARD_COST + 5 } })

    // Wait for SSE — PENDING should disappear
    await expect(pendingBadge).not.toBeVisible({ timeout: 5000 })
  })
})
