/**
 * selectUnpickedExternals returns external attendees that:
 *  - belong to the given LunchEvent
 *  - have an email on file
 *  - have NOT picked a dish (dishId is null)
 *
 * Externals without an email (can't be reminded) and externals who already have
 * a dish must be excluded.
 */
import { afterAll, describe, expect, it } from 'vitest'
import { prisma } from '../setup'
import { createTestProgram, cleanupTestData, uid } from '../helpers'
import { selectUnpickedExternals } from '@/server/services/lunch-reminders'

const programIds: string[] = []

afterAll(async () => {
  for (const programId of programIds) {
    await prisma.externalAttendee.deleteMany({ where: { lunchEvent: { programId } } })
    await prisma.dish.deleteMany({ where: { lunchEvent: { programId } } })
    await prisma.lunchEvent.deleteMany({ where: { programId } })
    await cleanupTestData(programId, [])
  }
})

describe('selectUnpickedExternals', () => {
  it('returns only emailed externals with no dish', async () => {
    const program = await createTestProgram({ name: `xfilter-${uid()}` })
    programIds.push(program.id)

    const event = await prisma.lunchEvent.create({
      data: { programId: program.id, enabled: true },
    })
    const dish = await prisma.dish.create({
      data: { lunchEventId: event.id, name: `dish-${uid()}` },
    })

    // emailed + no dish → INCLUDED
    const x1 = await prisma.externalAttendee.create({
      data: { lunchEventId: event.id, name: 'Has email, no dish', email: `a-${uid()}@x.test` },
    })
    // emailed + has dish → excluded
    await prisma.externalAttendee.create({
      data: {
        lunchEventId: event.id,
        name: 'Has email, has dish',
        email: `b-${uid()}@x.test`,
        dishId: dish.id,
      },
    })
    // no email + no dish → excluded (can't email them)
    await prisma.externalAttendee.create({
      data: { lunchEventId: event.id, name: 'No email', email: null },
    })

    const result = await selectUnpickedExternals(prisma, { id: event.id })

    const ids = result.map((x) => x.id)
    expect(ids).toContain(x1.id)
    expect(result).toHaveLength(1)
    expect(result[0].email).toBeTruthy()
  })
})
