import { suite } from '../lib/context.js'

suite('Lessons', { tags: ['lessons'] }, (t) => {
  // ─── Instructors: CRUD ───

  t.test('creates an instructor', { tags: ['instructors', 'create'] }, async () => {
    const res = await t.api.post('/v1/instructors', {
      displayName: 'Sarah Mitchell',
      bio: 'Piano and voice instructor with 10 years experience',
      instruments: ['Piano', 'Voice'],
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.displayName, 'Sarah Mitchell')
    t.assert.ok(res.data.id)
    t.assert.equal(res.data.isActive, true)
    t.assert.equal(res.data.instruments.length, 2)
    t.assert.equal(res.data.instruments[0], 'Piano')
  })

  t.test('creates an instructor with minimal fields', { tags: ['instructors', 'create'] }, async () => {
    const res = await t.api.post('/v1/instructors', {
      displayName: 'John Doe',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.displayName, 'John Doe')
    t.assert.equal(res.data.bio, null)
    t.assert.equal(res.data.instruments, null)
  })

  t.test('rejects instructor creation without display name', { tags: ['instructors', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/instructors', {})
    t.assert.status(res, 400)
  })

  t.test('gets instructor by id', { tags: ['instructors', 'read'] }, async () => {
    const created = await t.api.post('/v1/instructors', { displayName: 'Get By ID Instructor' })
    const res = await t.api.get(`/v1/instructors/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.displayName, 'Get By ID Instructor')
  })

  t.test('returns 404 for missing instructor', { tags: ['instructors', 'read'] }, async () => {
    const res = await t.api.get('/v1/instructors/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('updates an instructor', { tags: ['instructors', 'update'] }, async () => {
    const created = await t.api.post('/v1/instructors', { displayName: 'Before Update', bio: 'Old bio' })
    const res = await t.api.patch(`/v1/instructors/${created.data.id}`, {
      displayName: 'After Update',
      bio: 'New bio',
      instruments: ['Guitar', 'Bass'],
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.displayName, 'After Update')
    t.assert.equal(res.data.bio, 'New bio')
    t.assert.equal(res.data.instruments.length, 2)
  })

  t.test('soft-deletes an instructor', { tags: ['instructors', 'delete'] }, async () => {
    const created = await t.api.post('/v1/instructors', { displayName: 'To Delete' })
    const res = await t.api.del(`/v1/instructors/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.isActive, false)
  })

  // ─── Instructors: List, Search, Sort ───

  t.test('lists instructors with pagination', { tags: ['instructors', 'read', 'pagination'] }, async () => {
    await t.api.post('/v1/instructors', { displayName: 'List Test A' })
    await t.api.post('/v1/instructors', { displayName: 'List Test B' })

    const res = await t.api.get('/v1/instructors', { limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.length >= 2)
    t.assert.ok(res.data.pagination.total >= 2)
  })

  t.test('searches instructors by display name', { tags: ['instructors', 'search'] }, async () => {
    await t.api.post('/v1/instructors', { displayName: 'Searchable Piano Teacher' })

    const res = await t.api.get('/v1/instructors', { q: 'Piano Teacher' })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.some((i: any) => i.displayName === 'Searchable Piano Teacher'))
  })

  t.test('sorts instructors by display name descending', { tags: ['instructors', 'sort'] }, async () => {
    await t.api.post('/v1/instructors', { displayName: 'AAA First Instructor' })
    await t.api.post('/v1/instructors', { displayName: 'ZZZ Last Instructor' })

    const res = await t.api.get('/v1/instructors', { sort: 'display_name', order: 'desc', limit: 100 })
    t.assert.status(res, 200)
    const names = res.data.data.map((i: any) => i.displayName)
    const zIdx = names.findIndex((n: string) => n.includes('ZZZ'))
    const aIdx = names.findIndex((n: string) => n.includes('AAA'))
    t.assert.ok(zIdx < aIdx, 'ZZZ should come before AAA in desc order')
  })

  t.test('deleted instructor does not appear in list', { tags: ['instructors', 'delete', 'list'] }, async () => {
    const created = await t.api.post('/v1/instructors', { displayName: 'Ghost Instructor XYZ' })
    await t.api.del(`/v1/instructors/${created.data.id}`)

    const res = await t.api.get('/v1/instructors', { q: 'Ghost Instructor XYZ', limit: 100 })
    t.assert.equal(res.data.data.length, 0)
  })

  // ─── Lesson Types: CRUD ───

  t.test('creates a lesson type', { tags: ['lesson-types', 'create'] }, async () => {
    const res = await t.api.post('/v1/lesson-types', {
      name: '30-min Private Piano',
      instrument: 'Piano',
      durationMinutes: 30,
      lessonFormat: 'private',
      rateMonthly: 120,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.name, '30-min Private Piano')
    t.assert.equal(res.data.instrument, 'Piano')
    t.assert.equal(res.data.durationMinutes, 30)
    t.assert.equal(res.data.lessonFormat, 'private')
    t.assert.equal(res.data.rateMonthly, '120.00')
    t.assert.ok(res.data.id)
  })

  t.test('creates a group lesson type', { tags: ['lesson-types', 'create'] }, async () => {
    const res = await t.api.post('/v1/lesson-types', {
      name: '60-min Group Guitar',
      instrument: 'Guitar',
      durationMinutes: 60,
      lessonFormat: 'group',
      rateMonthly: 80,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.lessonFormat, 'group')
  })

  t.test('creates a lesson type with all three rate presets', { tags: ['lesson-types', 'create'] }, async () => {
    const res = await t.api.post('/v1/lesson-types', {
      name: 'Multi-Rate Type',
      durationMinutes: 30,
      rateWeekly: 35,
      rateMonthly: 120,
      rateQuarterly: 330,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.rateWeekly, '35.00')
    t.assert.equal(res.data.rateMonthly, '120.00')
    t.assert.equal(res.data.rateQuarterly, '330.00')
  })

  t.test('rejects lesson type without required fields', { tags: ['lesson-types', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/lesson-types', {})
    t.assert.status(res, 400)
  })

  t.test('rejects lesson type without duration', { tags: ['lesson-types', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/lesson-types', { name: 'No Duration' })
    t.assert.status(res, 400)
  })

  t.test('gets lesson type by id', { tags: ['lesson-types', 'read'] }, async () => {
    const created = await t.api.post('/v1/lesson-types', { name: 'Get By ID Type', durationMinutes: 45 })
    const res = await t.api.get(`/v1/lesson-types/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.name, 'Get By ID Type')
  })

  t.test('returns 404 for missing lesson type', { tags: ['lesson-types', 'read'] }, async () => {
    const res = await t.api.get('/v1/lesson-types/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('updates a lesson type', { tags: ['lesson-types', 'update'] }, async () => {
    const created = await t.api.post('/v1/lesson-types', { name: 'Before Update Type', durationMinutes: 30 })
    const res = await t.api.patch(`/v1/lesson-types/${created.data.id}`, {
      name: 'After Update Type',
      durationMinutes: 45,
      rateMonthly: 150,
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.name, 'After Update Type')
    t.assert.equal(res.data.durationMinutes, 45)
    t.assert.equal(res.data.rateMonthly, '150.00')
  })

  t.test('soft-deletes a lesson type', { tags: ['lesson-types', 'delete'] }, async () => {
    const created = await t.api.post('/v1/lesson-types', { name: 'To Delete Type', durationMinutes: 30 })
    const res = await t.api.del(`/v1/lesson-types/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.isActive, false)
  })

  // ─── Lesson Types: List, Search, Sort ───

  t.test('lists lesson types with pagination', { tags: ['lesson-types', 'read', 'pagination'] }, async () => {
    await t.api.post('/v1/lesson-types', { name: 'List Type A', durationMinutes: 30 })
    await t.api.post('/v1/lesson-types', { name: 'List Type B', durationMinutes: 60 })

    const res = await t.api.get('/v1/lesson-types', { limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.length >= 2)
    t.assert.ok(res.data.pagination.total >= 2)
  })

  t.test('searches lesson types by name', { tags: ['lesson-types', 'search'] }, async () => {
    await t.api.post('/v1/lesson-types', { name: 'Searchable Violin Lesson', instrument: 'Violin', durationMinutes: 30 })

    const res = await t.api.get('/v1/lesson-types', { q: 'Violin' })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.some((lt: any) => lt.name.includes('Violin')))
  })

  t.test('sorts lesson types by name descending', { tags: ['lesson-types', 'sort'] }, async () => {
    await t.api.post('/v1/lesson-types', { name: 'AAA First Type', durationMinutes: 30 })
    await t.api.post('/v1/lesson-types', { name: 'ZZZ Last Type', durationMinutes: 30 })

    const res = await t.api.get('/v1/lesson-types', { sort: 'name', order: 'desc', limit: 100 })
    t.assert.status(res, 200)
    const names = res.data.data.map((lt: any) => lt.name)
    const zIdx = names.findIndex((n: string) => n.includes('ZZZ'))
    const aIdx = names.findIndex((n: string) => n.includes('AAA'))
    t.assert.ok(zIdx < aIdx, 'ZZZ should come before AAA in desc order')
  })

  t.test('deleted lesson type does not appear in list', { tags: ['lesson-types', 'delete', 'list'] }, async () => {
    const created = await t.api.post('/v1/lesson-types', { name: 'Ghost Type XYZ', durationMinutes: 30 })
    await t.api.del(`/v1/lesson-types/${created.data.id}`)

    const res = await t.api.get('/v1/lesson-types', { q: 'Ghost Type XYZ', limit: 100 })
    t.assert.equal(res.data.data.length, 0)
  })

  // ─── Schedule Slots: CRUD ───

  t.test('creates a schedule slot', { tags: ['schedule-slots', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Slot Lesson', durationMinutes: 30 })

    const res = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 2, // Tuesday
      startTime: '16:00',
      room: 'Room A',
      maxStudents: 1,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.dayOfWeek, 2)
    t.assert.equal(res.data.startTime, '16:00:00')
    t.assert.equal(res.data.room, 'Room A')
    t.assert.equal(res.data.maxStudents, 1)
    t.assert.equal(res.data.isActive, true)
  })

  t.test('creates a group slot with higher max students', { tags: ['schedule-slots', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Group Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Group Lesson', durationMinutes: 60, lessonFormat: 'group' })

    const res = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 4, // Thursday
      startTime: '17:00',
      room: 'Room B',
      maxStudents: 6,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.maxStudents, 6)
  })

  t.test('rejects schedule slot without required fields', { tags: ['schedule-slots', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/schedule-slots', {})
    t.assert.status(res, 400)
  })

  t.test('rejects invalid day of week', { tags: ['schedule-slots', 'create', 'validation'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Day Validation Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Day Validation Type', durationMinutes: 30 })

    const res = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 7,
      startTime: '10:00',
    })
    t.assert.status(res, 400)
  })

  t.test('rejects invalid time format', { tags: ['schedule-slots', 'create', 'validation'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Time Validation Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Time Validation Type', durationMinutes: 30 })

    const res = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 1,
      startTime: '3pm',
    })
    t.assert.status(res, 400)
  })

  t.test('detects overlapping slot for same instructor, day, and time', { tags: ['schedule-slots', 'create', 'conflict'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Conflict Instructor' })
    const type1 = await t.api.post('/v1/lesson-types', { name: 'Conflict Type 1', durationMinutes: 30 })
    const type2 = await t.api.post('/v1/lesson-types', { name: 'Conflict Type 2', durationMinutes: 30 })

    const first = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: type1.data.id,
      dayOfWeek: 3,
      startTime: '14:00',
    })
    t.assert.status(first, 201)

    const second = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: type2.data.id,
      dayOfWeek: 3,
      startTime: '14:00',
    })
    t.assert.status(second, 409)
  })

  t.test('allows same time for different instructors', { tags: ['schedule-slots', 'create', 'conflict'] }, async () => {
    const instructor1 = await t.api.post('/v1/instructors', { displayName: 'No Conflict Instructor A' })
    const instructor2 = await t.api.post('/v1/instructors', { displayName: 'No Conflict Instructor B' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'No Conflict Type', durationMinutes: 30 })

    const first = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor1.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 1,
      startTime: '10:00',
    })
    t.assert.status(first, 201)

    const second = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor2.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 1,
      startTime: '10:00',
    })
    t.assert.status(second, 201)
  })

  t.test('gets schedule slot by id', { tags: ['schedule-slots', 'read'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Get Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Get Slot Type', durationMinutes: 30 })
    const created = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 5,
      startTime: '09:00',
    })

    const res = await t.api.get(`/v1/schedule-slots/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.dayOfWeek, 5)
  })

  t.test('returns 404 for missing schedule slot', { tags: ['schedule-slots', 'read'] }, async () => {
    const res = await t.api.get('/v1/schedule-slots/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('updates a schedule slot', { tags: ['schedule-slots', 'update'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Update Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Update Slot Type', durationMinutes: 30 })
    const created = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 0,
      startTime: '11:00',
      room: 'Old Room',
    })

    const res = await t.api.patch(`/v1/schedule-slots/${created.data.id}`, {
      room: 'New Room',
      maxStudents: 3,
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.room, 'New Room')
    t.assert.equal(res.data.maxStudents, 3)
  })

  t.test('creates a schedule slot with instructor rate overrides', { tags: ['schedule-slots', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Rates Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Rates Slot Type', durationMinutes: 30, rateMonthly: 100 })

    const res = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 1,
      startTime: '13:00',
      rateWeekly: 40,
      rateMonthly: 150,
      rateQuarterly: 400,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.rateWeekly, '40.00')
    t.assert.equal(res.data.rateMonthly, '150.00')
    t.assert.equal(res.data.rateQuarterly, '400.00')
  })

  t.test('updates schedule slot rates', { tags: ['schedule-slots', 'update'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Update Rates Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Update Rates Type', durationMinutes: 30 })
    const created = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 3,
      startTime: '09:00',
    })

    const res = await t.api.patch(`/v1/schedule-slots/${created.data.id}`, {
      rateWeekly: 35,
      rateMonthly: 120,
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.rateWeekly, '35.00')
    t.assert.equal(res.data.rateMonthly, '120.00')
    t.assert.equal(res.data.rateQuarterly, null)
  })

  t.test('update detects conflict when changing time', { tags: ['schedule-slots', 'update', 'conflict'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Update Conflict Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Update Conflict Type', durationMinutes: 30 })

    await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 2,
      startTime: '15:00',
    })
    const second = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 2,
      startTime: '16:00',
    })

    const res = await t.api.patch(`/v1/schedule-slots/${second.data.id}`, {
      startTime: '15:00',
    })
    t.assert.status(res, 409)
  })

  t.test('soft-deletes a schedule slot', { tags: ['schedule-slots', 'delete'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Delete Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Delete Slot Type', durationMinutes: 30 })
    const created = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 6,
      startTime: '12:00',
    })

    const res = await t.api.del(`/v1/schedule-slots/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.isActive, false)
  })

  // ─── Schedule Slots: List, Filter ───

  t.test('lists schedule slots with pagination', { tags: ['schedule-slots', 'read', 'pagination'] }, async () => {
    const res = await t.api.get('/v1/schedule-slots', { limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.pagination)
    t.assert.ok(res.data.data.length >= 1)
  })

  t.test('filters schedule slots by instructor', { tags: ['schedule-slots', 'filter'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Filter Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Filter Slot Type', durationMinutes: 30 })
    await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 1,
      startTime: '08:00',
    })

    const res = await t.api.get('/v1/schedule-slots', { instructorId: instructor.data.id, limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.every((s: any) => s.instructorId === instructor.data.id))
  })

  t.test('filters schedule slots by day of week', { tags: ['schedule-slots', 'filter'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Day Filter Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Day Filter Type', durationMinutes: 30 })
    await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 0,
      startTime: '13:00',
    })

    const res = await t.api.get('/v1/schedule-slots', { dayOfWeek: '0', limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.every((s: any) => s.dayOfWeek === 0))
  })

  t.test('deleted slot does not appear in list', { tags: ['schedule-slots', 'delete', 'list'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Ghost Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Ghost Slot Type', durationMinutes: 30 })
    const created = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 4,
      startTime: '19:00',
      room: 'Ghost Room XYZ',
    })
    await t.api.del(`/v1/schedule-slots/${created.data.id}`)

    const res = await t.api.get('/v1/schedule-slots', { q: 'Ghost Room XYZ', limit: 100 })
    t.assert.equal(res.data.data.length, 0)
  })

  t.test('deactivated slot frees the time for new slot', { tags: ['schedule-slots', 'create', 'conflict'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Reuse Slot Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Reuse Slot Type', durationMinutes: 30 })

    const first = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 5,
      startTime: '18:00',
    })
    t.assert.status(first, 201)
    await t.api.del(`/v1/schedule-slots/${first.data.id}`)

    const second = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 5,
      startTime: '18:00',
    })
    t.assert.status(second, 201)
  })

  // ─── Enrollments: CRUD ───

  t.test('creates an enrollment', { tags: ['enrollments', 'create'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Enrollment Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Emma', lastName: 'Chen' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Enrollment Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Enrollment Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 2,
      startTime: '16:00',
    })

    const res = await t.api.post('/v1/enrollments', {
      memberId: member.data.id,
      accountId: acct.data.id,
      scheduleSlotId: slot.data.id,
      instructorId: instructor.data.id,
      startDate: '2026-01-15',
      rate: 120,
      billingInterval: 1,
      billingUnit: 'month',
      notes: 'Beginner piano student',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.status, 'active')
    t.assert.equal(res.data.memberId, member.data.id)
    t.assert.equal(res.data.rate, '120.00')
    t.assert.equal(res.data.billingInterval, 1)
    t.assert.equal(res.data.billingUnit, 'month')
    t.assert.equal(res.data.startDate, '2026-01-15')
    t.assert.equal(res.data.makeupCredits, 0)
  })

  t.test('rejects enrollment without required fields', { tags: ['enrollments', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/enrollments', {})
    t.assert.status(res, 400)
  })

  t.test('enforces slot capacity', { tags: ['enrollments', 'create', 'capacity'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Capacity Account', billingMode: 'consolidated' })
    const m1 = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Student', lastName: 'One' })
    const m2 = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Student', lastName: 'Two' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Capacity Instructor' })
    const lessonType = await t.api.post('/v1/lesson-types', { name: 'Capacity Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id,
      lessonTypeId: lessonType.data.id,
      dayOfWeek: 3,
      startTime: '14:00',
      maxStudents: 1,
    })

    const first = await t.api.post('/v1/enrollments', {
      memberId: m1.data.id,
      accountId: acct.data.id,
      scheduleSlotId: slot.data.id,
      instructorId: instructor.data.id,
      startDate: '2026-01-15',
    })
    t.assert.status(first, 201)

    const second = await t.api.post('/v1/enrollments', {
      memberId: m2.data.id,
      accountId: acct.data.id,
      scheduleSlotId: slot.data.id,
      instructorId: instructor.data.id,
      startDate: '2026-01-15',
    })
    t.assert.status(second, 409)
  })

  t.test('prevents member from enrolling in conflicting time', { tags: ['enrollments', 'create', 'conflict'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Time Conflict Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Busy', lastName: 'Student' })
    const i1 = await t.api.post('/v1/instructors', { displayName: 'Conflict Instructor A' })
    const i2 = await t.api.post('/v1/instructors', { displayName: 'Conflict Instructor B' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Conflict LT', durationMinutes: 30 })

    const slot1 = await t.api.post('/v1/schedule-slots', {
      instructorId: i1.data.id, lessonTypeId: lt.data.id, dayOfWeek: 1, startTime: '10:00',
    })
    const slot2 = await t.api.post('/v1/schedule-slots', {
      instructorId: i2.data.id, lessonTypeId: lt.data.id, dayOfWeek: 1, startTime: '10:00',
    })

    const first = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot1.data.id, instructorId: i1.data.id, startDate: '2026-01-15',
    })
    t.assert.status(first, 201)

    const second = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot2.data.id, instructorId: i2.data.id, startDate: '2026-01-15',
    })
    t.assert.status(second, 409)
  })

  t.test('gets enrollment by id', { tags: ['enrollments', 'read'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Get Enrollment Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Get', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Get Enrollment Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Get Enrollment Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 4, startTime: '15:00',
    })
    const created = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-02-01',
    })

    const res = await t.api.get(`/v1/enrollments/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.id, created.data.id)
  })

  t.test('returns 404 for missing enrollment', { tags: ['enrollments', 'read'] }, async () => {
    const res = await t.api.get('/v1/enrollments/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('updates an enrollment', { tags: ['enrollments', 'update'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Update Enrollment Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Update', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Update Enrollment Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Update Enrollment Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 5, startTime: '17:00',
    })
    const created = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-02-01',
    })

    const res = await t.api.patch(`/v1/enrollments/${created.data.id}`, {
      rate: 150,
      billingInterval: 2,
      billingUnit: 'week',
      notes: 'Updated rate',
      endDate: '2026-06-30',
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.rate, '150.00')
    t.assert.equal(res.data.billingInterval, 2)
    t.assert.equal(res.data.billingUnit, 'week')
    t.assert.equal(res.data.notes, 'Updated rate')
    t.assert.equal(res.data.endDate, '2026-06-30')
  })

  // ─── Enrollments: Status Transitions ───

  t.test('status lifecycle: active → paused → active → cancelled', { tags: ['enrollments', 'status'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Status Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Status', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Status Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Status Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 6, startTime: '09:00',
    })
    const created = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    t.assert.equal(created.data.status, 'active')

    const paused = await t.api.post(`/v1/enrollments/${created.data.id}/status`, { status: 'paused' })
    t.assert.equal(paused.data.status, 'paused')

    const resumed = await t.api.post(`/v1/enrollments/${created.data.id}/status`, { status: 'active' })
    t.assert.equal(resumed.data.status, 'active')

    const cancelled = await t.api.post(`/v1/enrollments/${created.data.id}/status`, { status: 'cancelled' })
    t.assert.equal(cancelled.data.status, 'cancelled')
  })

  // ─── Enrollments: List, Filter ───

  t.test('lists enrollments with pagination', { tags: ['enrollments', 'read', 'pagination'] }, async () => {
    const res = await t.api.get('/v1/enrollments', { limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.pagination)
    t.assert.ok(res.data.data.length >= 1)
  })

  t.test('filters enrollments by instructor', { tags: ['enrollments', 'filter'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Filter Enrollment Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Filter', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Filter Enrollment Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Filter Enrollment Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 0, startTime: '11:00',
    })
    await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-03-01',
    })

    const res = await t.api.get('/v1/enrollments', { instructorId: instructor.data.id, limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.every((e: any) => e.instructorId === instructor.data.id))
  })

  t.test('filters enrollments by status', { tags: ['enrollments', 'filter'] }, async () => {
    const res = await t.api.get('/v1/enrollments', { status: 'active', limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.every((e: any) => e.status === 'active'))
  })

  // ─── Lesson Sessions: Generation ───

  t.test('generates sessions for an enrollment', { tags: ['sessions', 'generate'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Session Gen Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Session', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Session Gen Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Session Gen Type', durationMinutes: 30 })
    // Use Tuesday (2) for predictable scheduling
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 2, startTime: '16:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const res = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=4`)
    t.assert.status(res, 200)
    t.assert.ok(res.data.generated >= 1, 'should generate at least 1 session')
    t.assert.equal(res.data.sessions.length, res.data.generated)
    // All sessions should be on Tuesday
    for (const s of res.data.sessions) {
      t.assert.equal(s.status, 'scheduled')
      t.assert.equal(s.scheduledTime, '16:00:00')
      const dayOfWeek = new Date(s.scheduledDate + 'T00:00:00').getDay()
      t.assert.equal(dayOfWeek, 2, `session date ${s.scheduledDate} should be Tuesday`)
    }
  })

  t.test('session generation is idempotent', { tags: ['sessions', 'generate'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Idempotent Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Idemp', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Idempotent Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Idempotent Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 3, startTime: '14:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const first = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=4`)
    t.assert.ok(first.data.generated >= 1)

    const second = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=4`)
    t.assert.equal(second.data.generated, 0, 'second call should generate 0 new sessions')
  })

  // ─── Lesson Sessions: CRUD ───

  t.test('gets lesson session by id', { tags: ['sessions', 'read'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Get Session Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Get', lastName: 'Session' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Get Session Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Get Session Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 4, startTime: '10:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)
    t.assert.ok(gen.data.sessions.length >= 1)

    const res = await t.api.get(`/v1/lesson-sessions/${gen.data.sessions[0].id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.enrollmentId, enrollment.data.id)
    t.assert.equal(res.data.status, 'scheduled')
  })

  t.test('returns 404 for missing lesson session', { tags: ['sessions', 'read'] }, async () => {
    const res = await t.api.get('/v1/lesson-sessions/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('lists lesson sessions with filters', { tags: ['sessions', 'read', 'filter'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'List Session Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'List', lastName: 'Session' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'List Session Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'List Session Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 5, startTime: '15:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=4`)

    const res = await t.api.get('/v1/lesson-sessions', { enrollmentId: enrollment.data.id, limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.length >= 1)
    t.assert.ok(res.data.data.every((s: any) => s.enrollmentId === enrollment.data.id))
    t.assert.ok(res.data.pagination)
  })

  // ─── Lesson Sessions: Status ───

  t.test('marks a session as attended', { tags: ['sessions', 'status'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Attend Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Attend', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Attend Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Attend Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 1, startTime: '09:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)

    const res = await t.api.post(`/v1/lesson-sessions/${gen.data.sessions[0].id}/status`, { status: 'attended' })
    t.assert.status(res, 200)
    t.assert.equal(res.data.status, 'attended')
  })

  t.test('marks a session as missed', { tags: ['sessions', 'status'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Missed Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Missed', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Missed Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Missed Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 0, startTime: '11:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)

    const res = await t.api.post(`/v1/lesson-sessions/${gen.data.sessions[0].id}/status`, { status: 'missed' })
    t.assert.status(res, 200)
    t.assert.equal(res.data.status, 'missed')
  })

  t.test('cancels a session', { tags: ['sessions', 'status'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Cancel Session Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Cancel', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Cancel Session Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Cancel Session Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 6, startTime: '13:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)

    const res = await t.api.post(`/v1/lesson-sessions/${gen.data.sessions[0].id}/status`, { status: 'cancelled' })
    t.assert.status(res, 200)
    t.assert.equal(res.data.status, 'cancelled')
  })

  // ─── Lesson Sessions: Notes ───

  t.test('saves post-lesson notes and auto-sets notesCompletedAt', { tags: ['sessions', 'notes'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Notes Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Notes', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Notes Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Notes Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 3, startTime: '16:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)
    const sessionId = gen.data.sessions[0].id

    // Mark as attended first
    await t.api.post(`/v1/lesson-sessions/${sessionId}/status`, { status: 'attended' })

    const res = await t.api.post(`/v1/lesson-sessions/${sessionId}/notes`, {
      instructorNotes: 'Emma was distracted today',
      memberNotes: 'Great focus on scales. Left hand needs work.',
      homeworkAssigned: 'Practice Fur Elise bars 1-8 hands together',
      nextLessonGoals: 'Start bars 9-16',
      topicsCovered: ['Fur Elise', 'C Major Scale'],
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.instructorNotes, 'Emma was distracted today')
    t.assert.equal(res.data.memberNotes, 'Great focus on scales. Left hand needs work.')
    t.assert.equal(res.data.homeworkAssigned, 'Practice Fur Elise bars 1-8 hands together')
    t.assert.equal(res.data.topicsCovered.length, 2)
    t.assert.ok(res.data.notesCompletedAt, 'notesCompletedAt should be auto-set')
  })

  t.test('second notes save does not reset notesCompletedAt', { tags: ['sessions', 'notes'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Notes Idempotent Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Idemp', lastName: 'Notes' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Notes Idemp Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Notes Idemp Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 4, startTime: '11:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)
    const sessionId = gen.data.sessions[0].id

    const first = await t.api.post(`/v1/lesson-sessions/${sessionId}/notes`, { instructorNotes: 'First notes' })
    t.assert.ok(first.data.notesCompletedAt)
    const originalTimestamp = first.data.notesCompletedAt

    const second = await t.api.post(`/v1/lesson-sessions/${sessionId}/notes`, { memberNotes: 'Updated member notes' })
    t.assert.equal(second.data.notesCompletedAt, originalTimestamp, 'notesCompletedAt should not change')
    t.assert.equal(second.data.memberNotes, 'Updated member notes')
  })

  // ─── Lesson Sessions: Update ───

  t.test('updates actual start/end times', { tags: ['sessions', 'update'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Times Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Times', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Times Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Times Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 2, startTime: '15:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const gen = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)

    const res = await t.api.patch(`/v1/lesson-sessions/${gen.data.sessions[0].id}`, {
      actualStartTime: '15:05',
      actualEndTime: '15:32',
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.actualStartTime, '15:05:00')
    t.assert.equal(res.data.actualEndTime, '15:32:00')
  })

  t.test('filters sessions by date range', { tags: ['sessions', 'filter'] }, async () => {
    const res = await t.api.get('/v1/lesson-sessions', { dateFrom: '2026-01-01', dateTo: '2026-12-31', limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.pagination)
  })

  t.test('filters sessions by status', { tags: ['sessions', 'filter'] }, async () => {
    const res = await t.api.get('/v1/lesson-sessions', { status: 'scheduled', limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.every((s: any) => s.status === 'scheduled'))
  })

  // ─── Grading Scales: CRUD ───

  t.test('creates a grading scale with nested levels', { tags: ['grading-scales', 'create'] }, async () => {
    const res = await t.api.post('/v1/grading-scales', {
      name: 'Standard Letter',
      description: 'Traditional letter grades',
      isDefault: true,
      levels: [
        { value: 'A+', label: 'Excellent Plus', numericValue: 97, colorHex: '#4CAF50', sortOrder: 1 },
        { value: 'A', label: 'Excellent', numericValue: 93, colorHex: '#4CAF50', sortOrder: 2 },
        { value: 'A-', label: 'Excellent Minus', numericValue: 90, colorHex: '#8BC34A', sortOrder: 3 },
        { value: 'B+', label: 'Good Plus', numericValue: 87, colorHex: '#CDDC39', sortOrder: 4 },
        { value: 'B', label: 'Good', numericValue: 83, colorHex: '#CDDC39', sortOrder: 5 },
        { value: 'F', label: 'Fail', numericValue: 0, colorHex: '#F44336', sortOrder: 10 },
      ],
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.name, 'Standard Letter')
    t.assert.equal(res.data.isDefault, true)
    t.assert.equal(res.data.levels.length, 6)
    t.assert.equal(res.data.levels[0].value, 'A+')
    t.assert.equal(res.data.levels[0].numericValue, 97)
  })

  t.test('creates a progress scale', { tags: ['grading-scales', 'create'] }, async () => {
    const res = await t.api.post('/v1/grading-scales', {
      name: 'Progress',
      levels: [
        { value: 'Mastered', label: 'Skill fully mastered', numericValue: 100, colorHex: '#4CAF50', sortOrder: 1 },
        { value: 'Proficient', label: 'Near mastery', numericValue: 75, colorHex: '#8BC34A', sortOrder: 2 },
        { value: 'Developing', label: 'Making progress', numericValue: 50, colorHex: '#FFC107', sortOrder: 3 },
        { value: 'Beginning', label: 'Just started', numericValue: 25, colorHex: '#FF9800', sortOrder: 4 },
      ],
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.levels.length, 4)
  })

  t.test('rejects scale without levels', { tags: ['grading-scales', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/grading-scales', { name: 'Empty Scale', levels: [] })
    t.assert.status(res, 400)
  })

  t.test('rejects scale without name', { tags: ['grading-scales', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/grading-scales', { levels: [{ value: 'A', label: 'A', numericValue: 90, sortOrder: 1 }] })
    t.assert.status(res, 400)
  })

  t.test('gets grading scale with levels', { tags: ['grading-scales', 'read'] }, async () => {
    const created = await t.api.post('/v1/grading-scales', {
      name: 'Get Test Scale',
      levels: [
        { value: 'Pass', label: 'Passed', numericValue: 70, sortOrder: 1 },
        { value: 'Fail', label: 'Failed', numericValue: 0, sortOrder: 2 },
      ],
    })

    const res = await t.api.get(`/v1/grading-scales/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.name, 'Get Test Scale')
    t.assert.equal(res.data.levels.length, 2)
    t.assert.equal(res.data.levels[0].value, 'Pass')
  })

  t.test('returns 404 for missing grading scale', { tags: ['grading-scales', 'read'] }, async () => {
    const res = await t.api.get('/v1/grading-scales/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('lists grading scales with pagination', { tags: ['grading-scales', 'read', 'pagination'] }, async () => {
    const res = await t.api.get('/v1/grading-scales', { limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.length >= 2)
    t.assert.ok(res.data.pagination)
  })

  t.test('searches grading scales by name', { tags: ['grading-scales', 'search'] }, async () => {
    const res = await t.api.get('/v1/grading-scales', { q: 'Progress' })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.some((s: any) => s.name === 'Progress'))
  })

  t.test('lists all scales with levels (lookup endpoint)', { tags: ['grading-scales', 'read'] }, async () => {
    const res = await t.api.get('/v1/grading-scales/all')
    t.assert.status(res, 200)
    t.assert.ok(Array.isArray(res.data))
    t.assert.ok(res.data.length >= 2)
    t.assert.ok(res.data[0].levels, 'each scale should include levels')
  })

  t.test('updates a grading scale', { tags: ['grading-scales', 'update'] }, async () => {
    const created = await t.api.post('/v1/grading-scales', {
      name: 'Before Update Scale',
      levels: [{ value: 'A', label: 'Grade A', numericValue: 90, sortOrder: 1 }],
    })
    const res = await t.api.patch(`/v1/grading-scales/${created.data.id}`, { name: 'After Update Scale' })
    t.assert.status(res, 200)
    t.assert.equal(res.data.name, 'After Update Scale')
  })

  t.test('setting new default unsets previous default', { tags: ['grading-scales', 'update'] }, async () => {
    // First scale was created with isDefault: true
    const newDefault = await t.api.post('/v1/grading-scales', {
      name: 'New Default Scale',
      isDefault: true,
      levels: [{ value: 'OK', label: 'Okay', numericValue: 70, sortOrder: 1 }],
    })
    t.assert.equal(newDefault.data.isDefault, true)

    // Check all scales - only one should be default
    const allScales = await t.api.get('/v1/grading-scales/all')
    const defaults = allScales.data.filter((s: any) => s.isDefault === true)
    t.assert.equal(defaults.length, 1, 'only one scale should be default')
    t.assert.equal(defaults[0].id, newDefault.data.id)
  })

  t.test('soft-deletes a grading scale', { tags: ['grading-scales', 'delete'] }, async () => {
    const created = await t.api.post('/v1/grading-scales', {
      name: 'To Delete Scale',
      levels: [{ value: 'X', label: 'Delete Me', numericValue: 0, sortOrder: 1 }],
    })
    const res = await t.api.del(`/v1/grading-scales/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.isActive, false)

    const list = await t.api.get('/v1/grading-scales', { q: 'To Delete Scale', limit: 100 })
    t.assert.equal(list.data.data.length, 0)
  })

  // ─── Lesson Plans: Deep Create ───

  t.test('creates a lesson plan with nested sections and items', { tags: ['lesson-plans', 'create'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Plan Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Emma', lastName: 'Chen' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Plan Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Plan Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 2, startTime: '16:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-15',
    })

    const res = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id,
      enrollmentId: enrollment.data.id,
      title: 'Year 2 Piano',
      description: 'Second year curriculum',
      startedDate: '2026-01-15',
      sections: [
        {
          title: 'Scales & Arpeggios',
          sortOrder: 1,
          items: [
            { title: 'C Major 2 octaves', sortOrder: 1 },
            { title: 'G Major 2 octaves', sortOrder: 2 },
          ],
        },
        {
          title: 'Repertoire',
          sortOrder: 2,
          items: [
            { title: 'Minuet in G (Bach)', sortOrder: 1 },
            { title: 'Fur Elise (Beethoven)', sortOrder: 2 },
          ],
        },
        {
          title: 'Theory',
          sortOrder: 3,
          items: [
            { title: 'Key signatures to 2 sharps', sortOrder: 1 },
          ],
        },
      ],
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.title, 'Year 2 Piano')
    t.assert.equal(res.data.isActive, true)
    t.assert.equal(res.data.sections.length, 3)
    t.assert.equal(res.data.sections[0].title, 'Scales & Arpeggios')
    t.assert.equal(res.data.sections[0].items.length, 2)
    t.assert.equal(res.data.sections[1].items.length, 2)
    t.assert.equal(res.data.sections[2].items.length, 1)
    t.assert.equal(res.data.sections[0].items[0].status, 'not_started')
  })

  t.test('creating new plan deactivates previous active plan', { tags: ['lesson-plans', 'create'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Deactivate Plan Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Deact', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Deact Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Deact Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 3, startTime: '14:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const plan1 = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id,
      title: 'Plan 1', sections: [],
    })
    t.assert.equal(plan1.data.isActive, true)

    const plan2 = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id,
      title: 'Plan 2', sections: [],
    })
    t.assert.equal(plan2.data.isActive, true)

    // Check plan1 is now inactive
    const check = await t.api.get(`/v1/lesson-plans/${plan1.data.id}`)
    t.assert.equal(check.data.isActive, false)
  })

  // ─── Lesson Plans: Read ───

  t.test('gets lesson plan with sections, items, and progress', { tags: ['lesson-plans', 'read'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Get Plan Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Get', lastName: 'Plan' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Get Plan Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Get Plan Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 4, startTime: '10:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const created = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id,
      title: 'Progress Plan',
      sections: [{
        title: 'Skills', sortOrder: 1,
        items: [
          { title: 'Skill A', sortOrder: 1 },
          { title: 'Skill B', sortOrder: 2 },
        ],
      }],
    })

    const res = await t.api.get(`/v1/lesson-plans/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.title, 'Progress Plan')
    t.assert.equal(res.data.progress, 0, 'no items mastered yet')
    t.assert.equal(res.data.sections.length, 1)
    t.assert.equal(res.data.sections[0].items.length, 2)
  })

  t.test('returns 404 for missing lesson plan', { tags: ['lesson-plans', 'read'] }, async () => {
    const res = await t.api.get('/v1/lesson-plans/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('lists lesson plans with pagination', { tags: ['lesson-plans', 'read', 'pagination'] }, async () => {
    const res = await t.api.get('/v1/lesson-plans', { limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.length >= 1)
    t.assert.ok(res.data.pagination)
  })

  // ─── Lesson Plan Items: Status + Auto-Dates ───

  t.test('item status transition auto-sets startedDate and masteredDate', { tags: ['lesson-plans', 'items', 'status'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Item Status Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Item', lastName: 'Status' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Item Status Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Item Status Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 5, startTime: '15:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id,
      title: 'Status Plan',
      sections: [{
        title: 'Skills', sortOrder: 1,
        items: [{ title: 'Test Item', sortOrder: 1 }],
      }],
    })
    const itemId = plan.data.sections[0].items[0].id

    // not_started -> in_progress: sets startedDate
    const inProgress = await t.api.patch(`/v1/lesson-plan-items/${itemId}`, { status: 'in_progress' })
    t.assert.equal(inProgress.data.status, 'in_progress')
    t.assert.ok(inProgress.data.startedDate, 'startedDate should be set')
    t.assert.equal(inProgress.data.masteredDate, null)

    // in_progress -> mastered: sets masteredDate
    const mastered = await t.api.patch(`/v1/lesson-plan-items/${itemId}`, { status: 'mastered' })
    t.assert.equal(mastered.data.status, 'mastered')
    t.assert.ok(mastered.data.masteredDate, 'masteredDate should be set')

    // mastered -> in_progress: clears masteredDate
    const backToProgress = await t.api.patch(`/v1/lesson-plan-items/${itemId}`, { status: 'in_progress' })
    t.assert.equal(backToProgress.data.masteredDate, null, 'masteredDate should be cleared')
    t.assert.ok(backToProgress.data.startedDate, 'startedDate should remain')
  })

  t.test('progress percentage calculation with mastered and skipped items', { tags: ['lesson-plans', 'progress'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Progress Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Prog', lastName: 'Student' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Progress Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Progress Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 6, startTime: '11:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id,
      title: 'Progress Plan',
      sections: [{
        title: 'Skills', sortOrder: 1,
        items: [
          { title: 'Item A', sortOrder: 1 },
          { title: 'Item B', sortOrder: 2 },
          { title: 'Item C', sortOrder: 3 },
          { title: 'Item D (skip)', sortOrder: 4 },
        ],
      }],
    })

    const items = plan.data.sections[0].items
    await t.api.patch(`/v1/lesson-plan-items/${items[0].id}`, { status: 'mastered' })
    await t.api.patch(`/v1/lesson-plan-items/${items[3].id}`, { status: 'skipped' })

    // 1 mastered out of 3 non-skipped = 33%
    const res = await t.api.get(`/v1/lesson-plans/${plan.data.id}`)
    t.assert.equal(res.data.progress, 33)
  })

  t.test('updates a lesson plan title', { tags: ['lesson-plans', 'update'] }, async () => {
    const acct = await t.api.post('/v1/accounts', { name: 'Update Plan Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Update', lastName: 'Plan' })
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Update Plan Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Update Plan Type', durationMinutes: 30 })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 0, startTime: '09:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id,
      title: 'Before Update', sections: [],
    })

    const res = await t.api.patch(`/v1/lesson-plans/${plan.data.id}`, { title: 'After Update' })
    t.assert.status(res, 200)
    t.assert.equal(res.data.title, 'After Update')
  })

  // ─── Instructor Blocked Dates ───

  t.test('creates a blocked date for an instructor', { tags: ['blocked-dates', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Blocked Date Test Instructor' })
    const res = await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, {
      startDate: '2026-07-04',
      endDate: '2026-07-04',
      reason: 'Holiday',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.instructorId, instructor.data.id)
    t.assert.equal(res.data.startDate, '2026-07-04')
    t.assert.equal(res.data.endDate, '2026-07-04')
    t.assert.equal(res.data.reason, 'Holiday')
    t.assert.ok(res.data.id)
  })

  t.test('creates a multi-day blocked date range', { tags: ['blocked-dates', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Vacation Test Instructor' })
    const res = await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, {
      startDate: '2026-08-01',
      endDate: '2026-08-07',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.startDate, '2026-08-01')
    t.assert.equal(res.data.endDate, '2026-08-07')
    t.assert.equal(res.data.reason, null)
  })

  t.test('rejects blocked date with end before start', { tags: ['blocked-dates', 'create', 'validation'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Invalid Date Instructor' })
    const res = await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, {
      startDate: '2026-08-07',
      endDate: '2026-08-01',
    })
    t.assert.status(res, 409)
  })

  t.test('returns 404 for blocked date on missing instructor', { tags: ['blocked-dates', 'create'] }, async () => {
    const res = await t.api.post('/v1/instructors/a0000000-0000-0000-0000-999999999999/blocked-dates', {
      startDate: '2026-07-04',
      endDate: '2026-07-04',
    })
    t.assert.status(res, 404)
  })

  t.test('lists blocked dates for an instructor', { tags: ['blocked-dates', 'read'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'List Blocked Dates Instructor' })
    await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, { startDate: '2026-07-04', endDate: '2026-07-04' })
    await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, { startDate: '2026-08-01', endDate: '2026-08-07' })

    const res = await t.api.get(`/v1/instructors/${instructor.data.id}/blocked-dates`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.length, 2)
  })

  t.test('deletes a blocked date', { tags: ['blocked-dates', 'delete'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Delete Blocked Date Instructor' })
    const blocked = await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, {
      startDate: '2026-07-04',
      endDate: '2026-07-04',
    })
    const res = await t.api.del(`/v1/instructors/${instructor.data.id}/blocked-dates/${blocked.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.id, blocked.data.id)

    const list = await t.api.get(`/v1/instructors/${instructor.data.id}/blocked-dates`)
    t.assert.equal(list.data.length, 0)
  })

  t.test('session generation skips instructor blocked dates', { tags: ['blocked-dates', 'sessions', 'generate'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Blocked Gen Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Blocked Gen Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Blocked Gen Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Blocked', lastName: 'Gen' })

    // Find next Sunday (dayOfWeek=0) from today
    const today = new Date()
    const daysUntilSunday = (7 - today.getDay()) % 7 || 7
    const nextSunday = new Date(today)
    nextSunday.setDate(today.getDate() + daysUntilSunday)
    const sundayStr = nextSunday.toISOString().slice(0, 10)

    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 0, startTime: '10:00',
    })

    // Block the first upcoming Sunday
    await t.api.post(`/v1/instructors/${instructor.data.id}/blocked-dates`, {
      startDate: sundayStr,
      endDate: sundayStr,
    })

    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: sundayStr,
    })

    const res = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)
    t.assert.status(res, 200)

    // The blocked Sunday should not appear in generated sessions
    const sessions: Array<{ scheduledDate: string }> = res.data.sessions
    const hasBlockedDate = sessions.some((s) => s.scheduledDate === sundayStr)
    t.assert.equal(hasBlockedDate, false)
  })

  // ─── Store Closures ───

  t.test('creates a store closure', { tags: ['store-closures', 'create'] }, async () => {
    const res = await t.api.post('/v1/store-closures', {
      name: 'Christmas Break',
      startDate: '2026-12-24',
      endDate: '2026-12-26',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.name, 'Christmas Break')
    t.assert.equal(res.data.startDate, '2026-12-24')
    t.assert.equal(res.data.endDate, '2026-12-26')
    t.assert.ok(res.data.id)
  })

  t.test('rejects store closure with end before start', { tags: ['store-closures', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/store-closures', {
      name: 'Invalid',
      startDate: '2026-12-26',
      endDate: '2026-12-24',
    })
    t.assert.status(res, 409)
  })

  t.test('lists store closures', { tags: ['store-closures', 'read'] }, async () => {
    await t.api.post('/v1/store-closures', { name: 'Closure A', startDate: '2026-11-01', endDate: '2026-11-01' })
    await t.api.post('/v1/store-closures', { name: 'Closure B', startDate: '2026-11-15', endDate: '2026-11-15' })

    const res = await t.api.get('/v1/store-closures')
    t.assert.status(res, 200)
    t.assert.ok(Array.isArray(res.data))
    t.assert.ok(res.data.length >= 2)
  })

  t.test('deletes a store closure', { tags: ['store-closures', 'delete'] }, async () => {
    const created = await t.api.post('/v1/store-closures', {
      name: 'To Delete',
      startDate: '2026-10-01',
      endDate: '2026-10-01',
    })
    const res = await t.api.del(`/v1/store-closures/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.id, created.data.id)
  })

  t.test('session generation skips store closures', { tags: ['store-closures', 'sessions', 'generate'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Closure Gen Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Closure Gen Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Closure Gen Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Closure', lastName: 'Gen' })

    // Find next Monday (dayOfWeek=1) from today
    const today = new Date()
    const daysUntilMonday = (8 - today.getDay()) % 7 || 7
    const nextMonday = new Date(today)
    nextMonday.setDate(today.getDate() + daysUntilMonday)
    const mondayStr = nextMonday.toISOString().slice(0, 10)

    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 1, startTime: '11:00',
    })

    // Create a store closure covering the first upcoming Monday
    const closure = await t.api.post('/v1/store-closures', {
      name: 'Test Closure',
      startDate: mondayStr,
      endDate: mondayStr,
    })

    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: mondayStr,
    })

    const res = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions?weeks=2`)
    t.assert.status(res, 200)

    const sessions: Array<{ scheduledDate: string }> = res.data.sessions
    const hasClosedDate = sessions.some((s) => s.scheduledDate === mondayStr)
    t.assert.equal(hasClosedDate, false)

    // Clean up closure so it doesn't affect other tests
    await t.api.del(`/v1/store-closures/${closure.data.id}`)
  })

  // ─── Substitute Instructor ───

  t.test('assigns a substitute instructor to a session', { tags: ['sessions', 'substitute'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Primary Sub Instructor' })
    const sub = await t.api.post('/v1/instructors', { displayName: 'Substitute Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Sub Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Sub Test Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Sub', lastName: 'Student' })

    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 2, startTime: '14:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const genRes = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions`)
    const session = genRes.data.sessions[0]

    const res = await t.api.patch(`/v1/lesson-sessions/${session.id}`, {
      substituteInstructorId: sub.data.id,
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.substituteInstructorId, sub.data.id)
  })

  t.test('rejects substitute who is blocked on the session date', { tags: ['sessions', 'substitute', 'validation'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Primary Blocked Sub Test' })
    const sub = await t.api.post('/v1/instructors', { displayName: 'Blocked Sub' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Blocked Sub Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Blocked Sub Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Blocked', lastName: 'SubStudent' })

    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 3, startTime: '15:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const genRes = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions`)
    const session = genRes.data.sessions[0]

    // Block the sub on the session date
    await t.api.post(`/v1/instructors/${sub.data.id}/blocked-dates`, {
      startDate: session.scheduledDate,
      endDate: session.scheduledDate,
    })

    const res = await t.api.patch(`/v1/lesson-sessions/${session.id}`, {
      substituteInstructorId: sub.data.id,
    })
    t.assert.status(res, 409)
  })

  // ─── Grade History ───

  t.test('creates a grade record and updates item current grade', { tags: ['grades', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Grade Test Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Grade Test Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Grade Test Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Grade', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 4, startTime: '09:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Grade Test Plan',
      sections: [{ title: 'Section 1', sortOrder: 0, items: [{ title: 'Scale Practice', sortOrder: 0 }] }],
    })
    const item = plan.data.sections[0].items[0]

    const scale = await t.api.post('/v1/grading-scales', {
      name: 'Grade Test Scale',
      levels: [
        { value: 'B', label: 'Good', numericValue: 80, sortOrder: 0 },
        { value: 'A', label: 'Excellent', numericValue: 95, sortOrder: 1 },
      ],
    })

    const res = await t.api.post(`/v1/lesson-plan-items/${item.id}/grades`, {
      gradingScaleId: scale.data.id,
      gradeValue: 'B',
      notes: 'Good progress this week',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.record.gradeValue, 'B')
    t.assert.equal(res.data.item.currentGradeValue, 'B')
    t.assert.ok(res.data.record.id)
  })

  t.test('grading a not_started item auto-transitions to in_progress', { tags: ['grades', 'create', 'status'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Auto Transition Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Auto Transition Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Auto Transition Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Auto', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 5, startTime: '10:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Transition Plan',
      sections: [{ title: 'S1', sortOrder: 0, items: [{ title: 'Arpeggios', sortOrder: 0 }] }],
    })
    const item = plan.data.sections[0].items[0]
    t.assert.equal(item.status, 'not_started')

    const res = await t.api.post(`/v1/lesson-plan-items/${item.id}/grades`, { gradeValue: 'C' })
    t.assert.status(res, 201)
    t.assert.equal(res.data.item.status, 'in_progress')
    t.assert.ok(res.data.item.startedDate)
  })

  t.test('grade history is append-only — multiple grades accumulate', { tags: ['grades', 'history'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'History Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'History Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'History Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'History', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 6, startTime: '11:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'History Plan',
      sections: [{ title: 'S1', sortOrder: 0, items: [{ title: 'Technique', sortOrder: 0 }] }],
    })
    const item = plan.data.sections[0].items[0]

    await t.api.post(`/v1/lesson-plan-items/${item.id}/grades`, { gradeValue: 'C' })
    await t.api.post(`/v1/lesson-plan-items/${item.id}/grades`, { gradeValue: 'B' })
    await t.api.post(`/v1/lesson-plan-items/${item.id}/grades`, { gradeValue: 'A' })

    const res = await t.api.get(`/v1/lesson-plan-items/${item.id}/grade-history`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.length, 3)
    t.assert.equal(res.data[0].gradeValue, 'C')
    t.assert.equal(res.data[2].gradeValue, 'A')

    // Current grade on item should be the most recent
    const itemRes = await t.api.get(`/v1/lesson-plan-items/${item.id}/grade-history`)
    t.assert.equal(itemRes.data.length, 3)
  })

  t.test('returns 404 when grading missing item', { tags: ['grades', 'create', 'validation'] }, async () => {
    const res = await t.api.post('/v1/lesson-plan-items/a0000000-0000-0000-0000-999999999999/grades', {
      gradeValue: 'B',
    })
    t.assert.status(res, 404)
  })

  // ─── Session Plan Items ───

  t.test('links plan items to a session', { tags: ['session-plan-items', 'create'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Link Items Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Link Items Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Link Items Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Link', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 0, startTime: '16:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Link Plan',
      sections: [{
        title: 'S1', sortOrder: 0,
        items: [
          { title: 'Item 1', sortOrder: 0 },
          { title: 'Item 2', sortOrder: 1 },
        ],
      }],
    })
    const items = plan.data.sections[0].items
    const genRes = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions`)
    const session = genRes.data.sessions[0]

    const res = await t.api.post(`/v1/lesson-sessions/${session.id}/plan-items`, {
      lessonPlanItemIds: items.map((i: any) => i.id),
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.linked, 2)
    t.assert.equal(res.data.items.length, 2)
  })

  t.test('linking items to session auto-transitions not_started to in_progress', { tags: ['session-plan-items', 'status'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Link Transition Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Link Transition Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Link Transition Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'LinkTrans', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 1, startTime: '17:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Trans Plan',
      sections: [{ title: 'S1', sortOrder: 0, items: [{ title: 'New Item', sortOrder: 0 }] }],
    })
    const item = plan.data.sections[0].items[0]
    t.assert.equal(item.status, 'not_started')

    const genRes = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions`)
    const session = genRes.data.sessions[0]

    await t.api.post(`/v1/lesson-sessions/${session.id}/plan-items`, {
      lessonPlanItemIds: [item.id],
    })

    // Check item status via grade-history (item is updated in DB)
    const historyRes = await t.api.get(`/v1/lesson-plan-items/${item.id}/grade-history`)
    // Item should now be in_progress — verify by fetching the plan
    const planRes = await t.api.get(`/v1/lesson-plans/${plan.data.id}`)
    const updatedItem = planRes.data.sections[0].items[0]
    t.assert.equal(updatedItem.status, 'in_progress')
  })

  t.test('linking items is idempotent — no duplicates on re-link', { tags: ['session-plan-items', 'idempotent'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Idempotent Link Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Idempotent Link Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Idempotent Link Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Idemp', lastName: 'Link' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 2, startTime: '18:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Idemp Plan',
      sections: [{ title: 'S1', sortOrder: 0, items: [{ title: 'Item', sortOrder: 0 }] }],
    })
    const item = plan.data.sections[0].items[0]
    const genRes = await t.api.post(`/v1/enrollments/${enrollment.data.id}/generate-sessions`)
    const session = genRes.data.sessions[0]

    await t.api.post(`/v1/lesson-sessions/${session.id}/plan-items`, { lessonPlanItemIds: [item.id] })
    const res2 = await t.api.post(`/v1/lesson-sessions/${session.id}/plan-items`, { lessonPlanItemIds: [item.id] })
    t.assert.status(res2, 201)
    t.assert.equal(res2.data.linked, 0) // Already linked, nothing new

    const listRes = await t.api.get(`/v1/lesson-sessions/${session.id}/plan-items`)
    t.assert.status(listRes, 200)
    t.assert.equal(listRes.data.length, 1)
  })

  t.test('returns 404 when linking to missing session', { tags: ['session-plan-items', 'validation'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Missing Session Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Missing Session Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Missing Session Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Miss', lastName: 'Session' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 3, startTime: '19:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const plan = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Miss Plan',
      sections: [{ title: 'S1', sortOrder: 0, items: [{ title: 'Item', sortOrder: 0 }] }],
    })
    const item = plan.data.sections[0].items[0]

    const res = await t.api.post('/v1/lesson-sessions/a0000000-0000-0000-0000-999999999999/plan-items', {
      lessonPlanItemIds: [item.id],
    })
    t.assert.status(res, 404)
  })

  // ─── Lesson Plan Templates ───

  t.test('creates a template with sections and items', { tags: ['templates', 'create'] }, async () => {
    const res = await t.api.post('/v1/lesson-plan-templates', {
      name: 'Beginner Piano',
      instrument: 'Piano',
      skillLevel: 'beginner',
      sections: [
        {
          title: 'Technique',
          sortOrder: 0,
          items: [
            { title: 'Scales (C major)', sortOrder: 0 },
            { title: 'Hand position', sortOrder: 1 },
          ],
        },
        {
          title: 'Repertoire',
          sortOrder: 1,
          items: [{ title: 'Twinkle Twinkle', sortOrder: 0 }],
        },
      ],
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.name, 'Beginner Piano')
    t.assert.equal(res.data.instrument, 'Piano')
    t.assert.equal(res.data.skillLevel, 'beginner')
    t.assert.equal(res.data.sections.length, 2)
    t.assert.equal(res.data.sections[0].items.length, 2)
    t.assert.equal(res.data.sections[1].items.length, 1)
    t.assert.ok(res.data.id)
  })

  t.test('creates a minimal template with no sections', { tags: ['templates', 'create'] }, async () => {
    const res = await t.api.post('/v1/lesson-plan-templates', {
      name: 'Empty Template',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.skillLevel, 'all_levels')
    t.assert.equal(res.data.sections.length, 0)
  })

  t.test('gets a template by id', { tags: ['templates', 'read'] }, async () => {
    const created = await t.api.post('/v1/lesson-plan-templates', {
      name: 'Get By ID Template',
      sections: [{ title: 'S1', sortOrder: 0, items: [{ title: 'Item A', sortOrder: 0 }] }],
    })
    const res = await t.api.get(`/v1/lesson-plan-templates/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.name, 'Get By ID Template')
    t.assert.equal(res.data.sections[0].items[0].title, 'Item A')
  })

  t.test('returns 404 for missing template', { tags: ['templates', 'read'] }, async () => {
    const res = await t.api.get('/v1/lesson-plan-templates/a0000000-0000-0000-0000-999999999999')
    t.assert.status(res, 404)
  })

  t.test('lists templates with pagination and filtering', { tags: ['templates', 'read', 'pagination'] }, async () => {
    await t.api.post('/v1/lesson-plan-templates', { name: 'Guitar Beginner', instrument: 'Guitar', skillLevel: 'beginner' })
    await t.api.post('/v1/lesson-plan-templates', { name: 'Guitar Advanced', instrument: 'Guitar', skillLevel: 'advanced' })
    await t.api.post('/v1/lesson-plan-templates', { name: 'Violin Beginner', instrument: 'Violin', skillLevel: 'beginner' })

    const res = await t.api.get('/v1/lesson-plan-templates', { instrument: 'Guitar', limit: 100 })
    t.assert.status(res, 200)
    t.assert.ok(res.data.data.every((t: any) => t.instrument === 'Guitar'))
    t.assert.ok(res.data.data.length >= 2)
  })

  t.test('updates a template', { tags: ['templates', 'update'] }, async () => {
    const created = await t.api.post('/v1/lesson-plan-templates', { name: 'Before Update Template' })
    const res = await t.api.patch(`/v1/lesson-plan-templates/${created.data.id}`, {
      name: 'After Update Template',
      skillLevel: 'intermediate',
    })
    t.assert.status(res, 200)
    t.assert.equal(res.data.name, 'After Update Template')
    t.assert.equal(res.data.skillLevel, 'intermediate')
  })

  t.test('soft-deletes a template', { tags: ['templates', 'delete'] }, async () => {
    const created = await t.api.post('/v1/lesson-plan-templates', { name: 'Delete Template' })
    const res = await t.api.del(`/v1/lesson-plan-templates/${created.data.id}`)
    t.assert.status(res, 200)
    t.assert.equal(res.data.isActive, false)

    const listRes = await t.api.get('/v1/lesson-plan-templates', { q: 'Delete Template', limit: 100 })
    const found = listRes.data.data.find((t: any) => t.id === created.data.id)
    t.assert.falsy(found)
  })

  t.test('instantiates a template into a member lesson plan', { tags: ['templates', 'instantiate'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Template Inst Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Template Inst Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Template Inst Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Template', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 4, startTime: '08:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    const template = await t.api.post('/v1/lesson-plan-templates', {
      name: 'Piano Basics',
      sections: [
        { title: 'Technique', sortOrder: 0, items: [{ title: 'Finger exercises', sortOrder: 0 }] },
        { title: 'Songs', sortOrder: 1, items: [{ title: 'Ode to Joy', sortOrder: 0 }, { title: 'Minuet', sortOrder: 1 }] },
      ],
    })

    const res = await t.api.post(`/v1/lesson-plan-templates/${template.data.id}/create-plan`, {
      memberId: member.data.id,
      enrollmentId: enrollment.data.id,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.title, 'Piano Basics') // uses template name by default
    t.assert.equal(res.data.sections.length, 2)
    t.assert.equal(res.data.sections[0].items.length, 1)
    t.assert.equal(res.data.sections[1].items.length, 2)
    t.assert.equal(res.data.isActive, true)
    // Items are independent copies, not template IDs
    t.assert.notEqual(res.data.sections[0].items[0].id, template.data.sections[0].items[0].id)
  })

  t.test('instantiate uses custom title when provided', { tags: ['templates', 'instantiate'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Custom Title Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Custom Title Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Custom Title Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Custom', lastName: 'Title' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 5, startTime: '07:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const template = await t.api.post('/v1/lesson-plan-templates', { name: 'Generic Template' })

    const res = await t.api.post(`/v1/lesson-plan-templates/${template.data.id}/create-plan`, {
      memberId: member.data.id,
      enrollmentId: enrollment.data.id,
      title: 'Custom Plan Title',
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.title, 'Custom Plan Title')
  })

  t.test('instantiate deactivates previous active plan on enrollment', { tags: ['templates', 'instantiate'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Deactivate Plan Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Deactivate Plan Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Deactivate Plan Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Deact', lastName: 'Plan' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 6, startTime: '06:00',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })

    // Create an existing active plan
    const existing = await t.api.post('/v1/lesson-plans', {
      memberId: member.data.id, enrollmentId: enrollment.data.id, title: 'Old Plan', sections: [],
    })
    t.assert.equal(existing.data.isActive, true)

    const template = await t.api.post('/v1/lesson-plan-templates', { name: 'New Template' })
    const res = await t.api.post(`/v1/lesson-plan-templates/${template.data.id}/create-plan`, {
      memberId: member.data.id,
      enrollmentId: enrollment.data.id,
    })
    t.assert.status(res, 201)
    t.assert.equal(res.data.isActive, true)

    // Old plan should be inactive now
    const oldPlanRes = await t.api.get(`/v1/lesson-plans/${existing.data.id}`)
    t.assert.equal(oldPlanRes.data.isActive, false)
  })

  t.test('template changes do not affect already-instantiated plans', { tags: ['templates', 'instantiate'] }, async () => {
    const instructor = await t.api.post('/v1/instructors', { displayName: 'Isolation Instructor' })
    const lt = await t.api.post('/v1/lesson-types', { name: 'Isolation Type', durationMinutes: 30 })
    const acct = await t.api.post('/v1/accounts', { name: 'Isolation Account', billingMode: 'consolidated' })
    const member = await t.api.post(`/v1/accounts/${acct.data.id}/members`, { firstName: 'Iso', lastName: 'Student' })
    const slot = await t.api.post('/v1/schedule-slots', {
      instructorId: instructor.data.id, lessonTypeId: lt.data.id, dayOfWeek: 0, startTime: '07:30',
    })
    const enrollment = await t.api.post('/v1/enrollments', {
      memberId: member.data.id, accountId: acct.data.id,
      scheduleSlotId: slot.data.id, instructorId: instructor.data.id, startDate: '2026-01-01',
    })
    const template = await t.api.post('/v1/lesson-plan-templates', { name: 'Isolation Template' })

    const plan = await t.api.post(`/v1/lesson-plan-templates/${template.data.id}/create-plan`, {
      memberId: member.data.id,
      enrollmentId: enrollment.data.id,
    })

    // Rename the template — plan title should remain unchanged
    await t.api.patch(`/v1/lesson-plan-templates/${template.data.id}`, { name: 'Renamed Template' })

    const planRes = await t.api.get(`/v1/lesson-plans/${plan.data.id}`)
    t.assert.equal(planRes.data.title, 'Isolation Template') // original name preserved
  })
})
