"use strict";
const index = require("./orgDomains-W_rFTMBa.cjs");
const dayjs = require("dayjs");
const handleConfirmation = require("./handleConfirmation-5Kz8ZlmD.cjs");
const index$1 = require("./email-manager-w-Fd9mb6.cjs");
const Sentry = require("@sentry/nextjs");
const allowDisablingStandardEmails = require("./allowDisablingStandardEmails-ePazUekp.cjs");
const httpError = require("./http-error-mkY8Ke7V.cjs");
const getCalEventResponses = require("./getCalEventResponses--KV3bpgK.cjs");
const isPrismaObj = require("./isPrismaObj-fQw4PHjD.cjs");
const isRecurringEvent = require("./isRecurringEvent-QOFZ__d7.cjs");
const credential = require("./credential-9BNiqYc8.cjs");
const doesBookingRequireConfirmation = ({
  booking: { startTime, eventType }
}) => {
  let requiresConfirmation = eventType?.requiresConfirmation;
  const rcThreshold = eventType?.metadata?.requiresConfirmationThreshold;
  if (rcThreshold) {
    const startTimeUTC = dayjs(startTime).utc();
    const currentTime = dayjs();
    const timeDifference = startTimeUTC.diff(currentTime, rcThreshold.unit);
    if (timeDifference > rcThreshold.time) {
      requiresConfirmation = false;
    }
  }
  return requiresConfirmation;
};
const getWebhookPayloadForBooking = ({
  booking,
  evt
}) => {
  const eventTypeInfo = {
    eventTitle: booking.eventType?.title,
    eventDescription: booking.eventType?.description,
    requiresConfirmation: booking.eventType?.requiresConfirmation || null,
    price: booking.eventType?.price,
    currency: booking.eventType?.currency,
    length: booking.eventType?.length
  };
  const payload = {
    ...evt,
    ...eventTypeInfo,
    bookingId: booking.id
  };
  return payload;
};
const log$1 = index.logger.getSubLogger({ prefix: ["[handleBookingRequested] book:user"] });
async function handleBookingRequested(args) {
  const { evt, booking } = args;
  log$1.debug("Emails: Sending booking requested emails");
  await index$1.sendOrganizerRequestEmail({ ...evt }, booking?.eventType?.metadata);
  await index$1.sendAttendeeRequestEmailAndSMS(
    { ...evt },
    evt.attendees[0],
    booking?.eventType?.metadata
  );
  const orgId = await index$1.getOrgIdFromMemberOrTeamId({
    memberId: booking.userId,
    teamId: booking.eventType?.teamId
  });
  try {
    const subscribersBookingRequested = await handleConfirmation.getWebhooks({
      userId: booking.userId,
      eventTypeId: booking.eventTypeId,
      triggerEvent: index.WebhookTriggerEvents.BOOKING_REQUESTED,
      teamId: booking.eventType?.teamId,
      orgId
    });
    const webhookPayload = getWebhookPayloadForBooking({
      booking,
      evt
    });
    const promises = subscribersBookingRequested.map(
      (sub) => handleConfirmation.sendPayload(
        sub.secret,
        index.WebhookTriggerEvents.BOOKING_REQUESTED,
        (/* @__PURE__ */ new Date()).toISOString(),
        sub,
        webhookPayload
      ).catch((e) => {
        log$1.error(
          `Error executing webhook for event: ${index.WebhookTriggerEvents.BOOKING_REQUESTED}, URL: ${sub.subscriberUrl}, bookingId: ${evt.bookingId}, bookingUid: ${evt.uid}`,
          index.safeStringify(e)
        );
      })
    );
    await Promise.all(promises);
  } catch (error) {
    log$1.error("Error in handleBookingRequested", index.safeStringify(error));
  }
}
function getPlatformParams(platformOAuthClient) {
  return {
    platformClientId: platformOAuthClient.id,
    platformCancelUrl: platformOAuthClient.bookingCancelRedirectUri,
    platformRescheduleUrl: platformOAuthClient.bookingRescheduleRedirectUri,
    platformBookingUrl: platformOAuthClient.bookingRedirectUri,
    arePlatformEmailsEnabled: platformOAuthClient.areEmailsEnabled,
    areCalendarEventsEnabled: platformOAuthClient.areCalendarEventsEnabled
  };
}
class PlatformOAuthClientRepository {
  async getByUserId(userId) {
    try {
      return index.prisma.platformOAuthClient.findFirst({
        where: {
          users: {
            some: {
              id: userId
            }
          }
        }
      });
    } catch (err) {
      Sentry.captureException(err);
      throw err;
    }
  }
}
async function getEventType(id) {
  return index.prisma.eventType.findUnique({
    where: {
      id
    },
    select: {
      id: true,
      recurringEvent: true,
      requiresConfirmation: true,
      metadata: true
    }
  });
}
async function getBooking(bookingId) {
  const booking = await index.prisma.booking.findUnique({
    where: {
      id: bookingId
    },
    select: {
      ...index.bookingMinimalSelect,
      responses: true,
      eventType: {
        select: {
          currency: true,
          description: true,
          id: true,
          length: true,
          price: true,
          requiresConfirmation: true,
          hideOrganizerEmail: true,
          metadata: true,
          customReplyToEmail: true,
          title: true,
          teamId: true,
          parentId: true,
          parent: {
            select: {
              teamId: true
            }
          },
          slug: true,
          workflows: {
            select: {
              workflow: {
                select: index$1.workflowSelect
              }
            }
          },
          bookingFields: true,
          team: {
            select: {
              id: true,
              name: true,
              parentId: true
            }
          }
        }
      },
      metadata: true,
      smsReminderNumber: true,
      location: true,
      eventTypeId: true,
      userId: true,
      uid: true,
      paid: true,
      destinationCalendar: true,
      status: true,
      user: {
        select: {
          id: true,
          username: true,
          timeZone: true,
          credentials: { select: index.credentialForCalendarServiceSelect },
          timeFormat: true,
          email: true,
          name: true,
          locale: true,
          destinationCalendar: true,
          isPlatformManaged: true
        }
      }
    }
  });
  if (!booking)
    throw new httpError.HttpError({ statusCode: 204, message: "No booking found" });
  let eventTypeRaw = null;
  if (booking.eventTypeId) {
    eventTypeRaw = await getEventType(booking.eventTypeId);
  }
  const eventType = { ...eventTypeRaw, metadata: index.EventTypeMetaDataSchema.parse(eventTypeRaw?.metadata) };
  const { user: userWithoutDelegationCredentials } = booking;
  if (!userWithoutDelegationCredentials)
    throw new httpError.HttpError({ statusCode: 204, message: "No user found" });
  const user = await credential.enrichUserWithDelegationCredentials({
    user: userWithoutDelegationCredentials
  });
  const t = await index.getTranslation(user.locale ?? "en", "common");
  const attendeesListPromises = booking.attendees.map(async (attendee) => {
    return {
      name: attendee.name,
      email: attendee.email,
      timeZone: attendee.timeZone,
      language: {
        translate: await index.getTranslation(attendee.locale ?? "en", "common"),
        locale: attendee.locale ?? "en"
      }
    };
  });
  const organizerOrganizationProfile = await index.prisma.profile.findFirst({
    where: {
      userId: booking.userId ?? void 0
    }
  });
  const organizerOrganizationId = organizerOrganizationProfile?.organizationId;
  const bookerUrl = await index$1.getBookerBaseUrl(
    booking.eventType?.team?.parentId ?? organizerOrganizationId ?? null
  );
  const attendeesList = await Promise.all(attendeesListPromises);
  const selectedDestinationCalendar = booking.destinationCalendar || user.destinationCalendar;
  const evt = {
    type: booking?.eventType?.slug,
    title: booking.title,
    bookerUrl,
    description: booking.description || void 0,
    startTime: booking.startTime.toISOString(),
    endTime: booking.endTime.toISOString(),
    customInputs: isPrismaObj.isPrismaObjOrUndefined(booking.customInputs),
    ...getCalEventResponses.getCalEventResponses({
      booking,
      bookingFields: booking.eventType?.bookingFields || null
    }),
    organizer: {
      email: booking?.userPrimaryEmail ?? user.email,
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      name: user.name,
      timeZone: user.timeZone,
      timeFormat: index$1.getTimeFormatStringFromUserTimeFormat(user.timeFormat),
      language: { translate: t, locale: user.locale ?? "en" },
      id: user.id
    },
    hideOrganizerEmail: booking.eventType?.hideOrganizerEmail,
    team: !!booking.eventType?.team ? {
      name: booking.eventType.team.name,
      id: booking.eventType.team.id,
      members: []
    } : void 0,
    attendees: attendeesList,
    location: booking.location,
    uid: booking.uid,
    destinationCalendar: selectedDestinationCalendar ? [selectedDestinationCalendar] : [],
    recurringEvent: isRecurringEvent.parseRecurringEvent(eventType?.recurringEvent),
    customReplyToEmail: booking.eventType?.customReplyToEmail
  };
  return {
    booking,
    user,
    evt,
    eventType
  };
}
const log = index.logger.getSubLogger({ prefix: ["[handlePaymentSuccess]"] });
async function handlePaymentSuccess(paymentId, bookingId) {
  log.debug(`handling payment success for bookingId ${bookingId}`);
  const { booking, user: userWithCredentials, evt, eventType } = await getBooking(bookingId);
  if (booking.location)
    evt.location = booking.location;
  const bookingData = {
    paid: true,
    status: index.BookingStatus.ACCEPTED
  };
  const allCredentials = await handleConfirmation.getAllCredentialsIncludeServiceAccountKey(userWithCredentials, {
    ...booking.eventType,
    metadata: booking.eventType?.metadata
  });
  const isConfirmed = booking.status === index.BookingStatus.ACCEPTED;
  const platformOAuthClientRepository = new PlatformOAuthClientRepository();
  const platformOAuthClient = userWithCredentials.isPlatformManaged ? await platformOAuthClientRepository.getByUserId(userWithCredentials.id) : null;
  const areCalendarEventsEnabled = platformOAuthClient?.areCalendarEventsEnabled ?? true;
  const areEmailsEnabled = platformOAuthClient?.areEmailsEnabled ?? true;
  if (isConfirmed) {
    const apps = index.eventTypeAppMetadataOptionalSchema.parse(eventType?.metadata?.apps);
    const eventManager = new allowDisablingStandardEmails.EventManager({ ...userWithCredentials, credentials: allCredentials }, apps);
    const scheduleResult = areCalendarEventsEnabled ? await eventManager.create(evt) : allowDisablingStandardEmails.placeholderCreatedEvent;
    bookingData.references = { create: scheduleResult.referencesToCreate };
  }
  const requiresConfirmation = doesBookingRequireConfirmation({
    booking: {
      ...booking,
      eventType
    }
  });
  if (requiresConfirmation) {
    delete bookingData.status;
  }
  const paymentUpdate = index.prisma.payment.update({
    where: {
      id: paymentId
    },
    data: {
      success: true
    }
  });
  const bookingUpdate = index.prisma.booking.update({
    where: {
      id: booking.id
    },
    data: bookingData
  });
  await index.prisma.$transaction([paymentUpdate, bookingUpdate]);
  if (!isConfirmed) {
    if (!requiresConfirmation) {
      await handleConfirmation.handleConfirmation({
        user: { ...userWithCredentials, credentials: allCredentials },
        evt,
        prisma: index.prisma,
        bookingId: booking.id,
        booking,
        paid: true,
        platformClientParams: platformOAuthClient ? getPlatformParams(platformOAuthClient) : void 0
      });
    } else {
      await handleBookingRequested({
        evt,
        booking
      });
      log.debug(`handling booking request for eventId ${eventType.id}`);
    }
  } else if (areEmailsEnabled) {
    await index$1.sendScheduledEmailsAndSMS({ ...evt }, void 0, void 0, void 0, eventType.metadata);
  }
  throw new httpError.HttpError({
    statusCode: 200,
    message: `Booking with id '${booking.id}' was paid and confirmed.`
  });
}
exports.handlePaymentSuccess = handlePaymentSuccess;
