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

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

const CHILD_NAME = 'RewardNotifDenyChild'
const REWARD_NAME = 'RewardNotifDenyReward'
const REWARD_COST = 10
const INITIAL_POINTS = 30

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 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: 'notif e2e deny test', cost } })
  const list = await request.get('/api/reward/list')
  return (await list.json()).rewards?.find((r: any) => r.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 rewardSection(page: Page) {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Rewards' }),
  })
}

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

  let childId = ''
  let rewardId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME, INITIAL_POINTS)
    rewardId = await createReward(request, REWARD_NAME, REWARD_COST)

    await request.put(`/api/child/${childId}/set-rewards`, {
      data: { reward_ids: [rewardId] },
    })
  })

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

  test.beforeEach(async ({ request }) => {
    // Create a fresh pending request before each test
    await request.post(`/api/child/${childId}/request-reward`, {
      data: { reward_id: rewardId },
    })
  })

  test.afterEach(async ({ request }) => {
    // Clean up any unconsumed pending requests
    await request.post(`/api/child/${childId}/cancel-request-reward`, {
      data: { reward_id: rewardId },
    })
  })

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

  // 5.2 Pending reward card shows PENDING badge in ParentView
  test('Pending reward card shows PENDING badge in ParentView', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await expect(card).toContainText('PENDING')
  })

  // 5.3 Denying a reward request removes the PENDING badge
  test('Denying a reward request removes PENDING badge', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const before = await getPoints(page)

    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()

    // Look for the reject action in the dialog
    const denyBtn = page.getByRole('button', { name: 'Reject', exact: true })
    await expect(denyBtn).toBeVisible({ timeout: 5000 })
    await denyBtn.click()
    await expect(denyBtn).not.toBeVisible({ timeout: 5000 })
    await expect(card).not.toContainText('PENDING', { timeout: 5000 })

    // Points should be unchanged
    await expect(page.locator('.points .value')).toHaveText(String(before), { timeout: 5000 })
  })

  // 5.4 Denying a reward request clears it from the notification view
  test('Denying a reward request clears it from notification view', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()
    const denyBtn = page.getByRole('button', { name: 'Reject', exact: true })
    await expect(denyBtn).toBeVisible({ timeout: 5000 })
    await denyBtn.click()
    await expect(denyBtn).not.toBeVisible({ timeout: 5000 })

    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: REWARD_NAME })
    await expect(item).not.toBeVisible({ timeout: 5000 })
  })

  // 5.5 POST deny-reward-request returns 200 when pending request exists (API layer)
  test('POST deny-reward-request returns 200 when pending request exists', async ({ request }) => {
    const res = await request.post(`/api/child/${childId}/deny-reward-request`, {
      data: { reward_id: rewardId },
    })
    expect(res.status()).toBe(200)
  })

  // 5.6 POST deny-reward-request returns 200 with graceful message when no pending request
  test('POST deny-reward-request returns 200 gracefully when no pending request', async ({
    request,
  }) => {
    // Cancel existing request first (afterEach will also try but that's fine)
    await request.post(`/api/child/${childId}/cancel-request-reward`, {
      data: { reward_id: rewardId },
    })
    const res = await request.post(`/api/child/${childId}/deny-reward-request`, {
      data: { reward_id: rewardId },
    })
    // Backend returns 200 with a graceful "already resolved" message per the spec
    expect(res.status()).toBe(200)
    const body = await res.json()
    expect(body.message).toContain('already been resolved')
  })
})
