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

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

const CHILD_NAME = 'ChildSortChild'

// Scheduled chores — two with different deadline times
const SCHED_EARLY = 'CSort1SchedEarly'
const SCHED_LATE = 'CSort2SchedLate'
// General chore (no schedule)
const GENERAL_CHORE = 'CSort3General'
// Pending chore (child confirmed)
const PENDING_CHORE = 'CSort4Pending'
// Non-today chore (should be hidden in child view)
const NON_TODAY_CHORE = 'CSortHiddenNonToday'

// Rewards with different costs
const PENDING_REWARD = 'CSortRewardPending'
const CHEAP_REWARD = 'CSortRewardCheap'
const EXPENSIVE_REWARD = 'CSortRewardExpensive'

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

  let childId = ''
  let schedEarlyId = ''
  let schedLateId = ''
  let generalChoreId = ''
  let pendingChoreId = ''
  let nonTodayChoreId = ''
  let pendingRewardId = ''
  let cheapRewardId = ''
  let expensiveRewardId = ''

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

    schedEarlyId = await createTask(request, SCHED_EARLY)
    schedLateId = await createTask(request, SCHED_LATE)
    generalChoreId = await createTask(request, GENERAL_CHORE)
    pendingChoreId = await createTask(request, PENDING_CHORE)
    nonTodayChoreId = await createTask(request, NON_TODAY_CHORE)

    // Rewards: different costs so points_needed differs
    pendingRewardId = await createReward(request, PENDING_REWARD, 10)
    cheapRewardId = await createReward(request, CHEAP_REWARD, 15)
    expensiveRewardId = await createReward(request, EXPENSIVE_REWARD, 100)

    const allChoreIds = [schedEarlyId, schedLateId, generalChoreId, pendingChoreId, 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, cheapRewardId, expensiveRewardId] },
    })

    // Scheduled early: today with deadline at 23:00 (future deadline, low sort key)
    await request.put(`/api/child/${childId}/task/${schedEarlyId}/schedule`, {
      data: {
        mode: 'days',
        day_configs: [{ day: todayDayIndex(), hour: 23, minute: 0 }],
        default_hour: 23,
        default_minute: 0,
        default_has_deadline: true,
        enabled: true,
      },
    })

    // Scheduled late: today with deadline at 23:59 (future deadline, higher sort key)
    await request.put(`/api/child/${childId}/task/${schedLateId}/schedule`, {
      data: {
        mode: 'days',
        day_configs: [{ day: todayDayIndex(), hour: 23, minute: 59 }],
        default_hour: 23,
        default_minute: 59,
        default_has_deadline: true,
        enabled: true,
      },
    })

    // 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
    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 needed
  })

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

  test('Child chore sort: scheduled today (earliest deadline) → general → pending', async ({
    page,
  }) => {
    // Clear parent auth so the router allows /child routes
    await page.addInitScript(() => localStorage.removeItem('parentAuth'))
    await page.goto(`/child/${childId}`)
    const section = choreSection(page)
    await section.locator('.item-card').first().waitFor({ state: 'visible' })

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

    // Scheduled for today (priority 0) sorted by earliest deadline → earliest first
    const earlyIdx = names.indexOf(SCHED_EARLY)
    const lateIdx = names.indexOf(SCHED_LATE)
    // General (priority 1)
    const generalIdx = names.indexOf(GENERAL_CHORE)
    // Pending (priority 2)
    const pendingIdx = names.indexOf(PENDING_CHORE)

    expect(earlyIdx).toBeGreaterThanOrEqual(0)
    expect(lateIdx).toBeGreaterThanOrEqual(0)
    expect(generalIdx).toBeGreaterThanOrEqual(0)
    expect(pendingIdx).toBeGreaterThanOrEqual(0)

    // Scheduled → earliest first
    expect(earlyIdx).toBeLessThan(lateIdx)
    // Scheduled before general
    expect(lateIdx).toBeLessThan(generalIdx)
    // General before pending
    expect(generalIdx).toBeLessThan(pendingIdx)

    // Non-today chore should be hidden
    expect(names).not.toContain(NON_TODAY_CHORE)
  })

  test('Child reward sort: pending first, then ascending by points needed', async ({ page }) => {
    // Clear parent auth so the router allows /child routes
    await page.addInitScript(() => localStorage.removeItem('parentAuth'))
    await page.goto(`/child/${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 cheapIdx = names.indexOf(CHEAP_REWARD)
    const expensiveIdx = names.indexOf(EXPENSIVE_REWARD)

    expect(pendingIdx).toBeGreaterThanOrEqual(0)
    expect(cheapIdx).toBeGreaterThanOrEqual(0)
    expect(expensiveIdx).toBeGreaterThanOrEqual(0)

    // Pending first
    expect(pendingIdx).toBeLessThan(cheapIdx)
    expect(pendingIdx).toBeLessThan(expensiveIdx)

    // Then ascending by points_needed (cheap reward costs 15, expensive 100; child has 50 points)
    // Points needed: cheap = max(0, 15-50) = 0; expensive = max(0, 100-50) = 50
    // So cheap should come before expensive
    expect(cheapIdx).toBeLessThan(expensiveIdx)
  })
})
