import { i as isAttendeeAction, a as isSMSOrWhatsappAction, b as isSMSAction, s as scheduleSMSReminder, c as scheduleEmailReminder, d as isWhatsappAction, e as scheduleWhatsappReminder, f as isCalAIAction, g as scheduleAIPhoneCall } from "./internal-team-billing-KzrOQ4-q.js";
import { k as cancelSMS, l as getMessageBody, s as sendOrScheduleWorkflowEmails, m as checkSMSRateLimit } from "./email-manager-K3-nXYto.js";
import { w as withReporting, W as WorkflowTriggerEvents, p as prisma, d as WorkflowMethods, g as getTranslation, e as WorkflowActions, S as SchedulingType, f as SENDER_NAME } from "./i18n-49-r55rr.js";
import { f as formatCalEventExtended } from "./CalEventParser-gVLQw-Bk.js";
const processWorkflowStep = async (workflow, step, {
  smsReminderNumber,
  calendarEvent,
  emailAttendeeSendToOverride,
  hideBranding,
  seatReferenceUid
}) => {
  if (!step?.verifiedAt)
    return;
  const evt = formatCalEventExtended(calendarEvent);
  if (isSMSOrWhatsappAction(step.action)) {
    await checkSMSRateLimit({
      identifier: `sms:${workflow.teamId ? "team:" : "user:"}${workflow.teamId || workflow.userId}`,
      rateLimitingType: "sms"
    });
  }
  if (isSMSAction(step.action)) {
    const sendTo = step.action === WorkflowActions.SMS_ATTENDEE ? smsReminderNumber : step.sendTo;
    await scheduleSMSReminder({
      evt,
      reminderPhone: sendTo,
      triggerEvent: workflow.trigger,
      action: step.action,
      timeSpan: {
        time: workflow.time,
        timeUnit: workflow.timeUnit
      },
      message: step.reminderBody || "",
      workflowStepId: step.id,
      template: step.template,
      sender: step.sender,
      userId: workflow.userId,
      teamId: workflow.teamId,
      isVerificationPending: step.numberVerificationPending,
      seatReferenceUid,
      verifiedAt: step.verifiedAt
    });
  } else if (step.action === WorkflowActions.EMAIL_ATTENDEE || step.action === WorkflowActions.EMAIL_HOST || step.action === WorkflowActions.EMAIL_ADDRESS) {
    let sendTo = [];
    switch (step.action) {
      case WorkflowActions.EMAIL_ADDRESS:
        sendTo = [step.sendTo || ""];
        break;
      case WorkflowActions.EMAIL_HOST:
        sendTo = [evt.organizer?.email || ""];
        const schedulingType = evt.eventType.schedulingType;
        const isTeamEvent = schedulingType === SchedulingType.ROUND_ROBIN || schedulingType === SchedulingType.COLLECTIVE;
        if (isTeamEvent && evt.team?.members) {
          sendTo = sendTo.concat(evt.team.members.map((member) => member.email));
        }
        break;
      case WorkflowActions.EMAIL_ATTENDEE:
        const attendees = !!emailAttendeeSendToOverride ? [emailAttendeeSendToOverride] : evt.attendees?.map((attendee) => attendee.email);
        const limitGuestsDate = /* @__PURE__ */ new Date("2025-01-13");
        if (workflow.userId) {
          const user = await prisma.user.findUnique({
            where: {
              id: workflow.userId
            },
            select: {
              createdDate: true
            }
          });
          if (user?.createdDate && user.createdDate > limitGuestsDate) {
            sendTo = attendees.slice(0, 1);
          } else {
            sendTo = attendees;
          }
        } else {
          sendTo = attendees;
        }
        break;
    }
    await scheduleEmailReminder({
      evt,
      triggerEvent: workflow.trigger,
      action: step.action,
      timeSpan: {
        time: workflow.time,
        timeUnit: workflow.timeUnit
      },
      sendTo,
      emailSubject: step.emailSubject || "",
      emailBody: step.reminderBody || "",
      template: step.template,
      sender: step.sender || SENDER_NAME,
      workflowStepId: step.id,
      hideBranding,
      seatReferenceUid,
      includeCalendarEvent: step.includeCalendarEvent,
      verifiedAt: step.verifiedAt
    });
  } else if (isWhatsappAction(step.action)) {
    const sendTo = step.action === WorkflowActions.WHATSAPP_ATTENDEE ? smsReminderNumber : step.sendTo;
    await scheduleWhatsappReminder({
      evt,
      reminderPhone: sendTo,
      triggerEvent: workflow.trigger,
      action: step.action,
      timeSpan: {
        time: workflow.time,
        timeUnit: workflow.timeUnit
      },
      message: step.reminderBody || "",
      workflowStepId: step.id,
      template: step.template,
      userId: workflow.userId,
      teamId: workflow.teamId,
      isVerificationPending: step.numberVerificationPending,
      seatReferenceUid,
      verifiedAt: step.verifiedAt
    });
  } else if (isCalAIAction(step.action)) {
    await scheduleAIPhoneCall({
      evt,
      triggerEvent: workflow.trigger,
      timeSpan: {
        time: workflow.time,
        timeUnit: workflow.timeUnit
      },
      workflowStepId: step.id,
      userId: workflow.userId,
      teamId: workflow.teamId,
      seatReferenceUid,
      verifiedAt: step.verifiedAt
    });
  }
};
const _scheduleWorkflowReminders = async (args) => {
  const {
    workflows,
    smsReminderNumber,
    calendarEvent: evt,
    emailAttendeeSendToOverride = "",
    hideBranding,
    seatReferenceUid,
    isDryRun = false
  } = args;
  if (isDryRun || !workflows.length)
    return;
  for (const workflow of workflows) {
    if (workflow.steps.length === 0)
      continue;
    for (const step of workflow.steps) {
      await processWorkflowStep(workflow, step, {
        calendarEvent: evt,
        emailAttendeeSendToOverride,
        smsReminderNumber,
        hideBranding,
        seatReferenceUid
      });
    }
  }
};
const _sendCancelledReminders = async (args) => {
  const { smsReminderNumber, evt, workflows, hideBranding } = args;
  if (!workflows.length)
    return;
  for (const workflow of workflows) {
    if (workflow.trigger !== WorkflowTriggerEvents.EVENT_CANCELLED)
      continue;
    for (const step of workflow.steps) {
      await processWorkflowStep(workflow, step, {
        smsReminderNumber,
        hideBranding,
        calendarEvent: evt
      });
    }
  }
};
const _cancelScheduledMessagesAndScheduleEmails = async ({
  teamId,
  userId
}) => {
  const { CreditService } = await import("./credit-service-_dfNRvHW.js");
  let userIdsWithNoCredits = userId ? [userId] : [];
  if (teamId) {
    const teamMembers = await prisma.membership.findMany({
      where: {
        teamId,
        accepted: true
      }
    });
    const creditService = new CreditService();
    userIdsWithNoCredits = (await Promise.all(
      teamMembers.map(async (member) => {
        const hasCredits = await creditService.hasAvailableCredits({ userId: member.userId });
        return { userId: member.userId, hasCredits };
      })
    )).filter(({ hasCredits }) => !hasCredits).map(({ userId: userId2 }) => userId2);
  }
  const scheduledMessages = await prisma.workflowReminder.findMany({
    where: {
      workflowStep: {
        workflow: {
          OR: [
            {
              userId: {
                in: userIdsWithNoCredits
              }
            },
            ...teamId ? [{ teamId }] : []
          ]
        }
      },
      scheduled: true,
      OR: [{ cancelled: false }, { cancelled: null }],
      referenceId: {
        not: null
      },
      method: {
        in: [WorkflowMethods.SMS, WorkflowMethods.WHATSAPP]
      }
    },
    select: {
      referenceId: true,
      workflowStep: {
        select: {
          action: true
        }
      },
      scheduledDate: true,
      uuid: true,
      id: true,
      booking: {
        select: {
          attendees: {
            select: {
              email: true,
              locale: true
            }
          },
          user: {
            select: {
              email: true
            }
          }
        }
      }
    }
  });
  await Promise.allSettled(scheduledMessages.map((msg) => cancelSMS(msg.referenceId ?? "")));
  await Promise.allSettled(
    scheduledMessages.map(async (msg) => {
      if (msg.workflowStep?.action && isAttendeeAction(msg.workflowStep.action)) {
        const messageBody = await getMessageBody(msg.referenceId ?? "");
        const sendTo = msg.booking?.attendees?.[0];
        if (sendTo) {
          const t = await getTranslation(sendTo.locale ?? "en", "common");
          await sendOrScheduleWorkflowEmails({
            to: [sendTo.email],
            subject: t("notification_about_your_booking"),
            html: messageBody,
            replyTo: msg.booking?.user?.email ?? "",
            sendAt: msg.scheduledDate,
            referenceUid: msg.uuid || void 0
          });
        }
      }
    })
  );
  await prisma.workflowReminder.updateMany({
    where: {
      id: {
        in: scheduledMessages.map((msg) => msg.id)
      }
    },
    data: {
      method: WorkflowMethods.EMAIL,
      referenceId: null
    }
  });
};
const scheduleWorkflowReminders = withReporting(
  _scheduleWorkflowReminders,
  "scheduleWorkflowReminders"
);
const sendCancelledReminders = withReporting(_sendCancelledReminders, "sendCancelledReminders");
const cancelScheduledMessagesAndScheduleEmails = withReporting(
  _cancelScheduledMessagesAndScheduleEmails,
  "cancelScheduledMessagesAndScheduleEmails"
);
export {
  scheduleWorkflowReminders as a,
  cancelScheduledMessagesAndScheduleEmails as c,
  sendCancelledReminders as s
};
