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

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

const CHILD_NAME = 'ParentSortChild'
const PENDING_CHORE = 'Sort1Pending'
const GENERAL_CHORE = 'Sort2General'
const EXPIRED_CHORE = 'Sort3Expired'
const COMPLETED_CHORE = 'Sort4Completed'
const NON_TODAY_CHORE = 'Sort5NonToday'

const PENDING_REWARD = 'SortRewardPending'
const NORMAL_REWARD = 'SortRewardNormal'

const POINTS = 5
const REWARD_COST = 10
const INITIAL_CHILD_POINTS = 50

function todayDayIndex(): number {
  return new Date().getDay()
}

function nonTodayDayIndex(): number {
  return (new Date().getDay() + 1) % 7
}

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): 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: 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: 'sort 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('Parent mode sort order', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let pendingChoreId = ''
  let generalChoreId = ''
  let expiredChoreId = ''
  let completedChoreId = ''
  let nonTodayChoreId = ''
  let pendingRewardId = ''
  let normalRewardId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME, INITIAL_CHILD_POINTS)

    pendingChoreId = await createTask(request, PENDING_CHORE)
    generalChoreId = await createTask(request, GENERAL_CHORE)
    expiredChoreId = await createTask(request, EXPIRED_CHORE)
    completedChoreId = await createTask(request, COMPLETED_CHORE)
    nonTodayChoreId = await createTask(request, NON_TODAY_CHORE)
    pendingRewardId = await createReward(request, PENDING_REWARD, REWARD_COST)
    normalRewardId = await createReward(request, NORMAL_REWARD, REWARD_COST)

    const allChoreIds = [
      pendingChoreId,
      generalChoreId,
      expiredChoreId,
      completedChoreId,
      nonTodayChoreId,
    ]
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: allChoreIds, type: 'chore' },
    })
    await request.put(`/api/child/${childId}/set-rewards`, {
      data: { reward_ids: [pendingRewardId, normalRewardId] },
    })

    // Expired chore: scheduled today with deadline already passed (00:01)
    await request.put(`/api/child/${childId}/task/${expiredChoreId}/schedule`, {
      data: {
        mode: 'days',
        day_configs: [{ day: todayDayIndex(), hour: 0, minute: 1 }],
        default_hour: 0,
        default_minute: 1,
        default_has_deadline: true,
        enabled: true,
      },
    })

    // Completed chore: scheduled today (interval, no deadline), then trigger to approve
    await request.put(`/api/child/${childId}/task/${completedChoreId}/schedule`, {
      data: {
        mode: 'interval',
        interval_days: 1,
        anchor_date: new Date().toLocaleDateString('en-CA'),
        interval_has_deadline: false,
      },
    })
    await request.post(`/api/child/${childId}/trigger-task`, {
      data: { task_id: completedChoreId },
    })

    // Non-today chore: scheduled for a different day only
    await request.put(`/api/child/${childId}/task/${nonTodayChoreId}/schedule`, {
      data: {
        mode: 'days',
        day_configs: [{ day: nonTodayDayIndex(), hour: 8, minute: 0 }],
        default_hour: 8,
        default_minute: 0,
        default_has_deadline: true,
        enabled: true,
      },
    })

    // Pending chore: child confirms → creates pending status
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: pendingChoreId },
    })

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

    // General chore: no schedule, no changes needed
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
    for (const id of [
      pendingChoreId,
      generalChoreId,
      expiredChoreId,
      completedChoreId,
      nonTodayChoreId,
    ]) {
      if (id) await request.delete(`/api/task/${id}`)
    }
    for (const id of [pendingRewardId, normalRewardId]) {
      if (id) await request.delete(`/api/reward/${id}`)
    }
  })

  test('Parent chore sort: pending → general → expired → completed → unscheduled', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const section = choreSection(page)
    await section.locator('.item-card').first().waitFor({ state: 'visible' })

    const names = await section.locator('.item-card .item-name').allTextContents()

    // Expected order: pending(0) → general(1) → expired(2) → completed(3) → non-today(4)
    const pendingIdx = names.indexOf(PENDING_CHORE)
    const generalIdx = names.indexOf(GENERAL_CHORE)
    const expiredIdx = names.indexOf(EXPIRED_CHORE)
    const completedIdx = names.indexOf(COMPLETED_CHORE)
    const nonTodayIdx = names.indexOf(NON_TODAY_CHORE)

    expect(pendingIdx).toBeGreaterThanOrEqual(0)
    expect(generalIdx).toBeGreaterThanOrEqual(0)
    expect(expiredIdx).toBeGreaterThanOrEqual(0)
    expect(completedIdx).toBeGreaterThanOrEqual(0)
    expect(nonTodayIdx).toBeGreaterThanOrEqual(0)

    expect(pendingIdx).toBeLessThan(generalIdx)
    expect(generalIdx).toBeLessThan(expiredIdx)
    expect(expiredIdx).toBeLessThan(completedIdx)
    expect(completedIdx).toBeLessThan(nonTodayIdx)
  })

  test('Parent reward sort: pending requests appear first', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const section = rewardSection(page)
    await section.locator('.item-card').first().waitFor({ state: 'visible' })

    const names = await section.locator('.item-card .item-name').allTextContents()

    const pendingIdx = names.indexOf(PENDING_REWARD)
    const normalIdx = names.indexOf(NORMAL_REWARD)

    expect(pendingIdx).toBeGreaterThanOrEqual(0)
    expect(normalIdx).toBeGreaterThanOrEqual(0)
    expect(pendingIdx).toBeLessThan(normalIdx)
  })
})
