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

type PrismaLike = PrismaClient | Prisma.TransactionClient

/**
 * Ensure a MemberLunchPick row exists for the given AttendingMember.
 * No-ops when the parent program has no LunchEvent.
 * Idempotent — safe to call repeatedly.
 */
export async function ensureLunchPickForAttendingMember(
  prisma: PrismaLike,
  attendingMemberId: string,
): Promise<void> {
  const member = await prisma.attendingMember.findUnique({
    where: { id: attendingMemberId },
    select: {
      id: true,
      confirmation: { select: { project: { select: { programId: true } } } },
      lunchPick: { select: { id: true } },
    },
  })
  if (!member) return
  if (member.lunchPick) return
  const programId = member.confirmation.project.programId
  const lunchEvent = await prisma.lunchEvent.findUnique({
    where: { programId },
    select: { id: true },
  })
  if (!lunchEvent) return
  await prisma.memberLunchPick.create({
    data: { attendingMemberId: member.id },
  })
}
