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

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

const CHILD_NAME = 'DigestErrorChild'
const CHORE_NAME = 'DigestErrorChore'
const CHORE_POINTS = 5
const DIGEST_ACTION_BASE_URL = process.env.PLAYWRIGHT_BASE_URL || 'https://localhost:5173'

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 getUnauthContext(playwright: any) {
  return playwright.request.newContext({
    ignoreHTTPSErrors: true,
    baseURL: DIGEST_ACTION_BASE_URL,
  })
}

test.describe('Digest Action Token — Error Paths', () => {
  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' },
    })
    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}`)
  })

  // 8.1 Expired token returns 400
  test('Expired token returns 400', async ({ request, playwright }) => {
    const tokenRes = await request.post('/api/admin/test/digest-token', {
      data: {
        child_id: childId,
        entity_id: choreId,
        entity_type: 'chore',
        action: 'approve',
        expires_in_hours: -1,
      },
    })
    expect(tokenRes.status()).toBe(200)
    const expiredToken = (await tokenRes.json()).token

    const unauthCtx = await getUnauthContext(playwright)
    const res = await unauthCtx.get(`/api/digest-action/${expiredToken}`, { maxRedirects: 0 })
    expect(res.status()).toBe(400)
    expect(res.headers()['location']).toBeUndefined()
    await unauthCtx.dispose()
  })

  // 8.2 Already-used token returns 400 on second use
  test('Already-used token returns 400 on second use', async ({ request, playwright }) => {
    const tokenRes = await request.post('/api/admin/test/digest-token', {
      data: {
        child_id: childId,
        entity_id: choreId,
        entity_type: 'chore',
        action: 'deny',
      },
    })
    expect(tokenRes.status()).toBe(200)
    const token = (await tokenRes.json()).token

    const unauthCtx = await getUnauthContext(playwright)

    // First use — authenticated POST executes and consumes the token
    const first = await request.post(`/api/digest-action/${token}`)
    expect(first.status()).toBe(200)

    // Second use — token is consumed, unauthenticated GET should return 400
    const second = await unauthCtx.get(`/api/digest-action/${token}`, { maxRedirects: 0 })
    expect(second.status()).toBe(400)
    await unauthCtx.dispose()

    // Re-create a pending chore confirmation for subsequent tests
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: choreId },
    })
  })

  // 8.3 Tampered token returns 400
  test('Tampered token returns 400', async ({ request, playwright }) => {
    const tokenRes = await request.post('/api/admin/test/digest-token', {
      data: {
        child_id: childId,
        entity_id: choreId,
        entity_type: 'chore',
        action: 'approve',
      },
    })
    expect(tokenRes.status()).toBe(200)
    const validToken: string = (await tokenRes.json()).token

    // Tamper: replace the last character
    const lastChar = validToken[validToken.length - 1]
    const replacement = lastChar === 'a' ? 'b' : 'a'
    const tamperedToken = validToken.slice(0, -1) + replacement

    const unauthCtx = await getUnauthContext(playwright)
    const res = await unauthCtx.get(`/api/digest-action/${tamperedToken}`, { maxRedirects: 0 })
    expect(res.status()).toBe(400)
    await unauthCtx.dispose()
  })

  // 8.4 Completely fake token returns 400
  test('Completely fake token returns 400', async ({ playwright }) => {
    const unauthCtx = await getUnauthContext(playwright)
    const res = await unauthCtx.get('/api/digest-action/this-token-does-not-exist', {
      maxRedirects: 0,
    })
    expect(res.status()).toBe(400)
    await unauthCtx.dispose()
  })

  // 8.5 Error response is a plain HTML page with no redirect
  test('Error response is plain HTML with no Location header', async ({ request, playwright }) => {
    const tokenRes = await request.post('/api/admin/test/digest-token', {
      data: {
        child_id: childId,
        entity_id: choreId,
        entity_type: 'chore',
        action: 'approve',
        expires_in_hours: -1,
      },
    })
    const expiredToken = (await tokenRes.json()).token

    const unauthCtx = await getUnauthContext(playwright)
    const res = await unauthCtx.get(`/api/digest-action/${expiredToken}`, { maxRedirects: 0 })
    expect(res.status()).toBe(400)
    const contentType = res.headers()['content-type'] ?? ''
    expect(contentType).toContain('text/html')
    expect(res.headers()['location']).toBeUndefined()
    await unauthCtx.dispose()
  })
})
