"use strict";
const internalTeamBilling = require("./internal-team-billing-h6fcyPAB.cjs");
const index$1 = require("./email-manager-aaSsaN-j.cjs");
const index = require("./i18n-Bs8xJzoY.cjs");
const processWorkflowStep = async (workflow, step, {
  smsReminderNumber,
  calendarEvent: evt,
  emailAttendeeSendToOverride,
  hideBranding,
  seatReferenceUid
}) => {
  if (!step?.verifiedAt)
    return;
  if (internalTeamBilling.isSMSOrWhatsappAction(step.action)) {
    await index$1.checkSMSRateLimit({
      identifier: `sms:${workflow.teamId ? "team:" : "user:"}${workflow.teamId || workflow.userId}`,
      rateLimitingType: "sms"
    });
  }
  if (internalTeamBilling.isSMSAction(step.action)) {
    const sendTo = step.action === index.WorkflowActions.SMS_ATTENDEE ? smsReminderNumber : step.sendTo;
    await internalTeamBilling.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 === index.WorkflowActions.EMAIL_ATTENDEE || step.action === index.WorkflowActions.EMAIL_HOST || step.action === index.WorkflowActions.EMAIL_ADDRESS) {
    let sendTo = [];
    switch (step.action) {
      case index.WorkflowActions.EMAIL_ADDRESS:
        sendTo = [step.sendTo || ""];
        break;
      case index.WorkflowActions.EMAIL_HOST:
        sendTo = [evt.organizer?.email || ""];
        const schedulingType = evt.eventType.schedulingType;
        const isTeamEvent = schedulingType === index.SchedulingType.ROUND_ROBIN || schedulingType === index.SchedulingType.COLLECTIVE;
        if (isTeamEvent && evt.team?.members) {
          sendTo = sendTo.concat(evt.team.members.map((member) => member.email));
        }
        break;
      case index.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 index.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 internalTeamBilling.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 || index.SENDER_NAME,
      workflowStepId: step.id,
      hideBranding,
      seatReferenceUid,
      includeCalendarEvent: step.includeCalendarEvent,
      verifiedAt: step.verifiedAt
    });
  } else if (internalTeamBilling.isWhatsappAction(step.action)) {
    const sendTo = step.action === index.WorkflowActions.WHATSAPP_ATTENDEE ? smsReminderNumber : step.sendTo;
    await internalTeamBilling.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 (internalTeamBilling.isCalAIAction(step.action)) {
    await internalTeamBilling.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 !== index.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 Promise.resolve().then(() => require("./credit-service-AVbSlRcX.cjs"));
  let userIdsWithNoCredits = userId ? [userId] : [];
  if (teamId) {
    const teamMembers = await index.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 index.prisma.workflowReminder.findMany({
    where: {
      workflowStep: {
        workflow: {
          OR: [
            {
              userId: {
                in: userIdsWithNoCredits
              }
            },
            ...teamId ? [{ teamId }] : []
          ]
        }
      },
      scheduled: true,
      OR: [{ cancelled: false }, { cancelled: null }],
      referenceId: {
        not: null
      },
      method: {
        in: [index.WorkflowMethods.SMS, index.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) => index$1.cancelSMS(msg.referenceId ?? "")));
  await Promise.allSettled(
    scheduledMessages.map(async (msg) => {
      if (msg.workflowStep?.action && internalTeamBilling.isAttendeeAction(msg.workflowStep.action)) {
        const messageBody = await index$1.getMessageBody(msg.referenceId ?? "");
        const sendTo = msg.booking?.attendees?.[0];
        if (sendTo) {
          const t = await index.getTranslation(sendTo.locale ?? "en", "common");
          await index$1.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 index.prisma.workflowReminder.updateMany({
    where: {
      id: {
        in: scheduledMessages.map((msg) => msg.id)
      }
    },
    data: {
      method: index.WorkflowMethods.EMAIL,
      referenceId: null
    }
  });
};
const scheduleWorkflowReminders = index.withReporting(
  _scheduleWorkflowReminders,
  "scheduleWorkflowReminders"
);
const sendCancelledReminders = index.withReporting(_sendCancelledReminders, "sendCancelledReminders");
const cancelScheduledMessagesAndScheduleEmails = index.withReporting(
  _cancelScheduledMessagesAndScheduleEmails,
  "cancelScheduledMessagesAndScheduleEmails"
);
exports.cancelScheduledMessagesAndScheduleEmails = cancelScheduledMessagesAndScheduleEmails;
exports.scheduleWorkflowReminders = scheduleWorkflowReminders;
exports.sendCancelledReminders = sendCancelledReminders;
