"use strict";
const crypto = require("crypto");
const handlebars = require("handlebars");
const CalEventParser = require("./CalEventParser-60bHdlQO.cjs");
const index = require("./index-UtrZFBcS.cjs");
function addUTCOffset(data) {
  if (isEventPayload(data)) {
    if (data.organizer?.timeZone) {
      data.organizer.utcOffset = index.getUTCOffsetByTimezone(
        data.organizer.timeZone,
        data.startTime
      );
    }
    if (data.attendees?.length) {
      data.attendees.forEach((attendee) => {
        attendee.utcOffset = index.getUTCOffsetByTimezone(attendee.timeZone, data.startTime);
      });
    }
  }
  return data;
}
function getZapierPayload(data) {
  const attendees = data.attendees.map((attendee) => {
    return {
      name: attendee.name,
      email: attendee.email,
      timeZone: attendee.timeZone,
      utcOffset: attendee.utcOffset
    };
  });
  const t = data.organizer.language.translate;
  const location = CalEventParser.getHumanReadableLocationValue(data.location || "", t);
  const body = {
    title: data.title,
    description: data.description,
    customInputs: data.customInputs,
    responses: data.responses,
    userFieldsResponses: data.userFieldsResponses,
    startTime: data.startTime,
    endTime: data.endTime,
    location,
    status: data.status,
    cancellationReason: data.cancellationReason,
    user: {
      username: data.organizer.username,
      name: data.organizer.name,
      email: data.organizer.email,
      timeZone: data.organizer.timeZone,
      utcOffset: data.organizer.utcOffset,
      locale: data.organizer.locale
    },
    eventType: {
      title: data.eventTitle,
      description: data.eventDescription,
      requiresConfirmation: data.requiresConfirmation,
      price: data.price,
      currency: data.currency,
      length: data.length
    },
    attendees,
    createdAt: data.createdAt
  };
  return JSON.stringify(body);
}
function applyTemplate(template, data, contentType) {
  const compiled = handlebars.compile(template)(data).replace(/&quot;/g, '"');
  if (contentType === "application/json") {
    return JSON.stringify(jsonParse(compiled));
  }
  return compiled;
}
function jsonParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (e) {
  }
  return false;
}
function isOOOEntryPayload(data) {
  return "oooEntry" in data;
}
function isNoShowPayload(data) {
  return "message" in data;
}
function isEventPayload(data) {
  return !isNoShowPayload(data) && !isOOOEntryPayload(data);
}
const sendPayload = async (secretKey, triggerEvent, createdAt, webhook, data) => {
  const { appId, payloadTemplate: template } = webhook;
  const contentType = !template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
  data = addUTCOffset(data);
  let body;
  if (isEventPayload(data)) {
    data.description = data.description || data.additionalNotes;
    if (appId === "zapier") {
      body = getZapierPayload({ ...data, createdAt });
    }
  }
  if (body === void 0) {
    if (template && (isOOOEntryPayload(data) || isEventPayload(data) || isNoShowPayload(data))) {
      body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
    } else {
      body = JSON.stringify({
        triggerEvent,
        createdAt,
        payload: data
      });
    }
  }
  return _sendPayload(secretKey, webhook, body, contentType);
};
const sendGenericWebhookPayload = async ({
  secretKey,
  triggerEvent,
  createdAt,
  webhook,
  data,
  rootData
}) => {
  const body = JSON.stringify({
    // Added rootData props first so that using the known(i.e. triggerEvent, createdAt, payload) properties in rootData doesn't override the known properties
    ...rootData,
    triggerEvent,
    createdAt,
    payload: data
  });
  return _sendPayload(secretKey, webhook, body, "application/json");
};
const createWebhookSignature = (params) => params.secret ? crypto.createHmac("sha256", params.secret).update(`${params.body}`).digest("hex") : "no-secret-provided";
const _sendPayload = async (secretKey, webhook, body, contentType) => {
  const { subscriberUrl } = webhook;
  if (!subscriberUrl || !body) {
    throw new Error("Missing required elements to send webhook payload.");
  }
  const response = await fetch(subscriberUrl, {
    method: "POST",
    headers: {
      "Content-Type": contentType,
      "X-Cal-Signature-256": createWebhookSignature({ secret: secretKey, body })
    },
    redirect: "manual",
    body
  });
  const text = await response.text();
  return {
    ok: response.ok,
    status: response.status,
    ...text ? {
      message: text
    } : {}
  };
};
const sendPayload$1 = sendPayload;
exports.isEventPayload = isEventPayload;
exports.sendGenericWebhookPayload = sendGenericWebhookPayload;
exports.sendPayload = sendPayload$1;
