import "./index-rbwdGzy0.js";
import { a as sendGenericWebhookPayload } from "./sendPayload-94-N-Ckq.js";
import { l as logger, p as prisma, h as bookingMinimalSelect, b as safeStringify, aB as TimeUnit, Y as WebhookTriggerEvents, B as BookingStatus } from "./user--mpkKOwW.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { f as fetcher } from "./dailyApiFetcher-g6tCC8ko.js";
import { z } from "zod";
import dayjs from "dayjs";
const log$1 = logger.getSubLogger({ prefix: ["trigger-no-show-handler"] });
const getBooking = async (bookingId) => {
  const booking = await prisma.booking.findUniqueOrThrow({
    where: {
      id: bookingId
    },
    select: {
      ...bookingMinimalSelect,
      uid: true,
      location: true,
      status: true,
      isRecorded: true,
      eventTypeId: true,
      references: true,
      fromReschedule: true,
      eventType: {
        select: {
          id: true,
          teamId: true,
          parentId: true,
          hosts: {
            select: {
              userId: true,
              user: {
                select: {
                  email: true
                }
              }
            }
          },
          users: {
            select: {
              id: true,
              email: true
            }
          }
        }
      },
      user: {
        select: {
          id: true,
          timeZone: true,
          email: true,
          name: true,
          locale: true,
          destinationCalendar: true
        }
      }
    }
  });
  if (!booking) {
    log$1.error(
      "Couldn't find Booking Id:",
      safeStringify({
        bookingId
      })
    );
    throw new HttpError({
      message: `Booking of id ${bookingId} does not exist or does not contain daily video as location`,
      statusCode: 404
    });
  }
  return booking;
};
const TIME_UNIT = [TimeUnit.DAY, TimeUnit.HOUR, TimeUnit.MINUTE];
const commonSchema = z.object({
  triggerEvent: z.enum([
    WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
    WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW
  ]),
  bookingId: z.number()
});
const ZWebhook = z.object({
  id: z.string(),
  subscriberUrl: z.string().url(),
  appId: z.string().nullable(),
  secret: z.string().nullable(),
  time: z.number(),
  timeUnit: z.enum(TIME_UNIT),
  eventTriggers: z.array(z.string()),
  payloadTemplate: z.string().nullable()
});
const triggerNoShowPayloadSchema = z.object({
  total_count: z.number(),
  data: z.array(
    z.object({
      id: z.string(),
      room: z.string(),
      start_time: z.number(),
      duration: z.number(),
      max_participants: z.number(),
      participants: z.array(
        z.object({
          user_id: z.string().nullable(),
          participant_id: z.string(),
          user_name: z.string(),
          join_time: z.number(),
          duration: z.number()
        })
      )
    }).passthrough()
  )
});
const ZSendNoShowWebhookPayloadSchema = commonSchema.extend({
  webhook: ZWebhook
});
const getMeetingSessionsFromRoomName = async (roomName) => {
  return fetcher(`/meetings?room=${roomName}`).then(triggerNoShowPayloadSchema.parse);
};
function getHosts(booking) {
  const hostMap = /* @__PURE__ */ new Map();
  const addHost = (id, email) => {
    if (!hostMap.has(id)) {
      hostMap.set(id, { id, email });
    }
  };
  booking?.eventType?.hosts?.forEach((host) => addHost(host.userId, host.user.email));
  booking?.eventType?.users?.forEach((user) => addHost(user.id, user.email));
  if (booking?.user?.id && booking?.user?.email) {
    addHost(booking.user.id, booking.user.email);
  }
  const attendeeEmails = new Set(booking.attendees?.map((attendee) => attendee.email));
  const filteredHosts = Array.from(hostMap.values()).filter(
    (host) => attendeeEmails.has(host.email) || host.id === booking.user?.id
  );
  return filteredHosts;
}
function sendWebhookPayload(webhook, triggerEvent, booking, maxStartTime, participants, originalRescheduledBooking, hostEmail) {
  const maxStartTimeHumanReadable = dayjs.unix(maxStartTime).format("YYYY-MM-DD HH:mm:ss Z");
  return sendGenericWebhookPayload({
    secretKey: webhook.secret,
    triggerEvent,
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    webhook,
    data: {
      title: booking.title,
      bookingId: booking.id,
      bookingUid: booking.uid,
      startTime: booking.startTime,
      attendees: booking.attendees,
      endTime: booking.endTime,
      participants,
      ...!!hostEmail ? { hostEmail } : {},
      ...originalRescheduledBooking ? { rescheduledBy: originalRescheduledBooking.rescheduledBy } : {},
      eventType: {
        ...booking.eventType,
        id: booking.eventTypeId,
        hosts: void 0,
        users: void 0
      },
      webhook: {
        ...webhook,
        secret: void 0
      },
      message: triggerEvent === WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW ? `Guest didn't join the call or didn't join before ${maxStartTimeHumanReadable}` : `Host with email ${hostEmail} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`
    }
  }).catch((e) => {
    console.error(
      `Error executing webhook for event: ${triggerEvent}, URL: ${webhook.subscriberUrl}`,
      webhook,
      e
    );
  });
}
function calculateMaxStartTime(startTime, time, timeUnit) {
  return dayjs(startTime).add(time, timeUnit.toLowerCase()).unix();
}
function checkIfUserJoinedTheCall(userId, allParticipants) {
  return allParticipants.some(
    (participant) => participant.user_id && parseInt(participant.user_id) === userId
  );
}
const getUserById = async (userId) => {
  return prisma.user.findUnique({
    where: { id: userId }
  });
};
async function getParticipantsWithEmail(allParticipants) {
  const participantsWithEmail = await Promise.all(
    allParticipants.map(async (participant) => {
      if (!participant.user_id)
        return participant;
      const user = await getUserById(parseInt(participant.user_id));
      return { ...participant, email: user?.email };
    })
  );
  return participantsWithEmail;
}
const log = logger.getSubLogger({ prefix: ["triggerNoShowTask"] });
const prepareNoShowTrigger = async (payload) => {
  const { bookingId, webhook } = ZSendNoShowWebhookPayloadSchema.parse(JSON.parse(payload));
  const booking = await getBooking(bookingId);
  let originalRescheduledBooking = null;
  if (booking.fromReschedule) {
    originalRescheduledBooking = await prisma.booking.findFirst({
      where: {
        uid: booking.fromReschedule,
        status: {
          in: [BookingStatus.ACCEPTED, BookingStatus.CANCELLED, BookingStatus.PENDING]
        }
      },
      select: {
        rescheduledBy: true
      }
    });
  }
  if (booking.status !== BookingStatus.ACCEPTED) {
    log.debug(
      "Booking is not accepted",
      safeStringify({
        bookingId,
        webhook: { id: webhook.id }
      })
    );
    return;
  }
  const dailyVideoReference = booking.references?.filter((reference) => reference.type === "daily_video")?.pop() ?? null;
  if (!dailyVideoReference) {
    log.error(
      "Daily video reference not found",
      safeStringify({
        bookingId,
        webhook: { id: webhook.id }
      })
    );
    throw new Error(`Daily video reference not found in triggerHostNoShow with bookingId ${bookingId}`);
  }
  const meetingDetails = await getMeetingSessionsFromRoomName(dailyVideoReference.uid);
  const hosts = getHosts(booking);
  const allParticipants = meetingDetails.data.flatMap((meeting) => meeting.participants);
  const hostsThatJoinedTheCall = [];
  const hostsThatDidntJoinTheCall = [];
  for (const host of hosts) {
    if (checkIfUserJoinedTheCall(host.id, allParticipants)) {
      hostsThatJoinedTheCall.push(host);
    } else {
      hostsThatDidntJoinTheCall.push(host);
    }
  }
  const numberOfHostsThatJoined = hosts.length - hostsThatDidntJoinTheCall.length;
  const didGuestJoinTheCall = meetingDetails.data.some(
    (meeting) => meeting.max_participants > numberOfHostsThatJoined
  );
  const participantsWithEmail = await getParticipantsWithEmail(allParticipants);
  return {
    hostsThatDidntJoinTheCall,
    hostsThatJoinedTheCall,
    booking,
    numberOfHostsThatJoined,
    webhook,
    didGuestJoinTheCall,
    originalRescheduledBooking,
    participants: participantsWithEmail
  };
};
export {
  calculateMaxStartTime as c,
  log as l,
  prepareNoShowTrigger as p,
  sendWebhookPayload as s
};
