import type { PrismaClient } from '@prisma/client'

/**
 * Return all AttendingMember rows (with user) that:
 *  - belong to a CONFIRMED FinalistConfirmation in the given program
 *  - have NOT yet picked a lunch dish (no MemberLunchPick row OR pick row with pickedAt=null)
 *
 * This is extracted from the cron so it can be unit-tested independently and
 * reused by the manual `sendReminders` admin action.
 *
 * Bug context: Prisma `lunchPick: { is: { pickedAt: null } }` only matches rows
 * that EXIST but have pickedAt=null.  Attendees with no pick row at all fall
 * through.  The correct filter is the OR form below.
 */
export async function selectUnpickedAttendees(
  prisma: PrismaClient,
  event: { id: string; programId: string },
) {
  return prisma.attendingMember.findMany({
    where: {
      confirmation: {
        project: { programId: event.programId },
        status: 'CONFIRMED',
      },
      OR: [
        { lunchPick: { is: null } },
        { lunchPick: { is: { pickedAt: null } } },
      ],
    },
    include: { user: { select: { name: true, email: true } } },
  })
}

/**
 * Return external attendees for a LunchEvent that can still be chased for a dish
 * pick: they have an email on file and have not yet been assigned a dish.
 * Externals with no email (un-emailable) or an existing dish are excluded.
 */
export async function selectUnpickedExternals(
  prisma: PrismaClient,
  event: { id: string },
) {
  return prisma.externalAttendee.findMany({
    where: {
      lunchEventId: event.id,
      dishId: null,
      AND: [{ email: { not: null } }, { email: { not: '' } }],
    },
  })
}
