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

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

const CHILD_NAME = 'RewardNotifApproveChild'
const REWARD_NAME = 'RewardNotifApproveReward'
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 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 — Appearance and In-App Grant', () => {
  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] },
    })

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

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

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

  // 4.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: REWARD_NAME })
    await expect(item).toBeVisible({ timeout: 5000 })
    await expect(item).toContainText(CHILD_NAME)
  })

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

  // 4.4 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')
  })

  // 4.5 Clicking a pending reward card opens the grant confirmation dialog
  test('Clicking a pending reward card opens grant confirmation dialog', 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()
    // A confirm dialog should appear — look for a confirmation button
    const confirmBtn = page.getByRole('button', { name: /yes|confirm|grant/i })
    await expect(confirmBtn).toBeVisible({ timeout: 5000 })
  })

  // 4.6 Confirming the grant removes PENDING badge and updates child points
  test('Confirming grant removes PENDING badge and updates child points', 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()
    const confirmBtn = page.getByRole('button', { name: /yes|confirm|grant/i })
    await expect(confirmBtn).toBeVisible({ timeout: 5000 })
    await confirmBtn.click()
    await expect(confirmBtn).not.toBeVisible({ timeout: 5000 })
    await expect(card).not.toContainText('PENDING', { timeout: 5000 })
    await expect(page.locator('.points .value')).toHaveText(String(before - REWARD_COST), {
      timeout: 5000,
    })
  })

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