"use strict";
const index = require("./email-manager-PJbiqghj.cjs");
const libphonenumberJs = require("libphonenumber-js");
const z = require("zod");
const indexBrowser = require("./index-browser-RtwB1hqI.cjs");
const bookingResponsesDbSchema = z.record(indexBrowser.dbReadResponseSchema);
const ensureValidPhoneNumber = (value) => {
  if (!value)
    return "";
  return value.replace(/^ +/, "+");
};
function getBookingResponsesSchema({ bookingFields, view }) {
  const schema = indexBrowser.bookingResponses.and(z.record(z.any()));
  return preprocess({ schema, bookingFields, isPartialSchema: false, view });
}
function preprocess({
  schema,
  bookingFields,
  isPartialSchema,
  view: currentView,
  checkOptional = false
}) {
  const preprocessed = z.preprocess(
    (responses) => {
      const parsedResponses = z.record(z.any()).nullable().parse(responses) || {};
      const newResponses = {};
      if (!bookingFields)
        return parsedResponses;
      bookingFields.forEach((field) => {
        const value = parsedResponses[field.name];
        if (value === void 0) {
          return;
        }
        const views = field.views;
        const isFieldApplicableToCurrentView = currentView === "ALL_VIEWS" ? true : views ? views.find((view) => view.id === currentView) : true;
        if (!isFieldApplicableToCurrentView) {
          return;
        }
        const fieldTypeSchema = indexBrowser.fieldTypesSchemaMap[field.type];
        if (fieldTypeSchema) {
          newResponses[field.name] = fieldTypeSchema.preprocess({
            response: value,
            isPartialSchema,
            field
          });
          return;
        }
        if (field.type === "boolean") {
          newResponses[field.name] = value === "true" || value === true;
        } else if (field.type === "multiemail" || field.type === "checkbox" || field.type === "multiselect") {
          newResponses[field.name] = value instanceof Array ? value : [value];
        } else if (field.type === "radioInput" && typeof value === "string") {
          let parsedValue = {
            optionValue: "",
            value: ""
          };
          try {
            parsedValue = JSON.parse(value);
          } catch (e) {
          }
          const optionsInputs = field.optionsInputs;
          const optionInputField = optionsInputs?.[parsedValue.value];
          if (optionInputField && optionInputField.type === "phone") {
            parsedValue.optionValue = ensureValidPhoneNumber(parsedValue.optionValue);
          }
          newResponses[field.name] = parsedValue;
        } else if (field.type === "phone") {
          newResponses[field.name] = ensureValidPhoneNumber(value);
        } else {
          newResponses[field.name] = value;
        }
      });
      return {
        ...parsedResponses,
        ...newResponses
      };
    },
    schema.superRefine(async (responses, ctx) => {
      if (!bookingFields) {
        return;
      }
      const attendeePhoneNumberField = bookingFields.find((field) => field.name === "attendeePhoneNumber");
      const isAttendeePhoneNumberFieldHidden = attendeePhoneNumberField?.hidden;
      const emailField = bookingFields.find((field) => field.name === "email");
      const isEmailFieldHidden = !!emailField?.hidden;
      if (isEmailFieldHidden && !isAttendeePhoneNumberFieldHidden) {
        responses["email"] = "";
      }
      for (const bookingField of bookingFields) {
        const value = responses[bookingField.name];
        const stringSchema = z.string();
        const emailSchema = isPartialSchema ? z.string() : z.string().refine(indexBrowser.emailSchemaRefinement);
        const phoneSchema = isPartialSchema ? z.string() : z.string().refine(async (val) => {
          return libphonenumberJs.isValidPhoneNumber(val);
        });
        const m = (message) => `{${bookingField.name}}${message}`;
        const views = bookingField.views;
        const isFieldApplicableToCurrentView = currentView === "ALL_VIEWS" ? true : views ? views.find((view) => view.id === currentView) : true;
        let hidden = bookingField.hidden;
        const numOptions = bookingField.options?.length ?? 0;
        if (bookingField.hideWhenJustOneOption) {
          hidden = hidden || numOptions <= 1;
        }
        let isRequired = false;
        if (!hidden && isFieldApplicableToCurrentView) {
          isRequired = checkOptional || !!bookingField.required;
        }
        if ((isPartialSchema || !isRequired) && value === void 0) {
          continue;
        }
        if (isRequired && !isPartialSchema && !value) {
          ctx.addIssue({ code: z.ZodIssueCode.custom, message: m(`error_required_field`) });
          return;
        }
        if (bookingField.type === "email") {
          if (!bookingField.hidden && checkOptional ? true : bookingField.required) {
            if (!emailSchema.safeParse(value).success) {
              ctx.addIssue({
                code: z.ZodIssueCode.custom,
                message: m("email_validation_error")
              });
            }
            const bookerEmail = value;
            const excludedEmails = bookingField.excludeEmails?.split(",").map((domain) => domain.trim()) || [];
            const match = excludedEmails.find((email) => bookerEmail.includes(email));
            if (match) {
              ctx.addIssue({
                code: z.ZodIssueCode.custom,
                message: m("exclude_emails_match_found_error_message")
              });
            }
            const requiredEmails = bookingField.requireEmails?.split(",").map((domain) => domain.trim()).filter(Boolean) || [];
            const requiredEmailsMatch = requiredEmails.find((email) => bookerEmail.includes(email));
            if (requiredEmails.length > 0 && !requiredEmailsMatch) {
              ctx.addIssue({
                code: z.ZodIssueCode.custom,
                message: m("require_emails_no_match_found_error_message")
              });
            }
          }
          continue;
        }
        const fieldTypeSchema = indexBrowser.fieldTypesSchemaMap[bookingField.type];
        if (fieldTypeSchema) {
          fieldTypeSchema.superRefine({
            response: value,
            ctx,
            m,
            field: bookingField,
            isPartialSchema
          });
          continue;
        }
        if (bookingField.type === "multiemail") {
          const emailsParsed = emailSchema.array().safeParse(value);
          if (isRequired && (!value || value.length === 0)) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: m(`error_required_field`) });
            continue;
          }
          if (!emailsParsed.success) {
            if (bookingField.name === "guests" && value.every((email) => email === "")) {
              responses[bookingField.name] = [];
              continue;
            }
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: m("email_validation_error")
            });
            continue;
          }
          const emails = emailsParsed.data;
          emails.sort().some((item, i) => {
            if (item === emails[i + 1]) {
              ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("duplicate_email") });
              return true;
            }
          });
          continue;
        }
        if (bookingField.type === "multiselect") {
          if (isRequired && (!value || value.length === 0)) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: m(`error_required_field`) });
            continue;
          }
          if (!stringSchema.array().safeParse(value).success) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid array of strings") });
          }
          continue;
        }
        if (bookingField.type === "checkbox") {
          if (!stringSchema.array().safeParse(value).success) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid array of strings") });
          }
          continue;
        }
        if (bookingField.type === "phone") {
          const needsValidation = isRequired || value && value.trim() !== "";
          if (!bookingField.hidden && needsValidation) {
            if (!(await phoneSchema.safeParseAsync(value)).success) {
              ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("invalid_number") });
            }
          }
          continue;
        }
        if (bookingField.type === "boolean") {
          const schema2 = z.boolean();
          if (!schema2.safeParse(value).success) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid Boolean") });
          }
          continue;
        }
        if (bookingField.type === "radioInput") {
          if (bookingField.optionsInputs) {
            const optionValue = value?.optionValue;
            const optionField = bookingField.optionsInputs[value?.value];
            const typeOfOptionInput = optionField?.type;
            if (
              // Either the field is required or there is a radio selected, we need to check if the optionInput is required or not.
              (isRequired || value?.value) && checkOptional ? true : optionField?.required && !optionValue
            ) {
              ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("error_required_field") });
              return;
            }
            if (optionValue) {
              if (typeOfOptionInput === "phone") {
                if (!(await phoneSchema.safeParseAsync(optionValue)).success) {
                  ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("invalid_number") });
                }
              }
            }
          }
          continue;
        }
        if (["address", "text", "select", "number", "radio", "textarea"].includes(bookingField.type)) {
          const schema2 = stringSchema;
          if (!schema2.safeParse(value).success) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid string") });
          }
          continue;
        }
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: `Can't parse unknown booking field type: ${bookingField.type}`
        });
      }
    })
  );
  if (isPartialSchema) {
    return preprocessed.catch(function(res) {
      console.error("Failed to preprocess query params, prefilling will be skipped", res?.error);
      return {};
    });
  }
  return preprocessed;
}
const contructEmailFromPhoneNumber = (phoneNumber) => {
  const cleanedPhoneNumber = phoneNumber.replace(/\+/g, "");
  return `${cleanedPhoneNumber}@sms.cal.com`;
};
function getResponsesFromOldBooking(rawBooking) {
  const customInputs = rawBooking.customInputs || {};
  const responses = Object.keys(customInputs).reduce((acc, label) => {
    acc[indexBrowser.slugify(label)] = customInputs[label];
    return acc;
  }, {});
  return {
    // It is possible to have no attendees in a booking when the booking is cancelled.
    name: rawBooking.attendees[0]?.name || "Nameless",
    email: rawBooking.attendees[0]?.email || "",
    guests: rawBooking.attendees.slice(1).map((attendee) => {
      return attendee.email;
    }),
    notes: rawBooking.description || "",
    location: {
      value: rawBooking.location || "",
      optionValue: rawBooking.location || ""
    },
    ...responses
  };
}
const getBookingWithResponses = (booking) => {
  return {
    ...booking,
    responses: bookingResponsesDbSchema.parse(booking.responses || getResponsesFromOldBooking(booking))
  };
};
const getCalEventResponses = ({
  bookingFields,
  booking,
  responses
}) => {
  const calEventUserFieldsResponses = {};
  const calEventResponses = {};
  const parsedBookingFields = bookingFields ? indexBrowser.eventTypeBookingFields.parse(bookingFields) : null;
  const backwardCompatibleResponses = responses ?? (booking ? getBookingWithResponses(booking).responses : null);
  if (!backwardCompatibleResponses)
    throw new Error("Couldn't get responses");
  if (!!!backwardCompatibleResponses.email) {
    if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string")
      throw new Error("Both Phone and Email are missing");
    backwardCompatibleResponses.email = contructEmailFromPhoneNumber(
      backwardCompatibleResponses["attendeePhoneNumber"]
    );
  }
  if (parsedBookingFields) {
    parsedBookingFields.forEach((field) => {
      const label = field.label || field.defaultLabel;
      if (!label) {
        throw new Error(`Missing label for booking field "${field.name}"`);
      }
      if (field.name == "guests" && field.hidden) {
        backwardCompatibleResponses[field.name] = [];
      }
      if (field.editable === "user" || field.editable === "user-readonly") {
        calEventUserFieldsResponses[field.name] = {
          label,
          value: backwardCompatibleResponses[field.name],
          isHidden: !!field.hidden
        };
      }
      calEventResponses[field.name] = {
        label,
        value: backwardCompatibleResponses[field.name],
        isHidden: !!field.hidden
      };
    });
  } else {
    for (const [name, value] of Object.entries(backwardCompatibleResponses)) {
      const isSystemField = index.SystemField.safeParse(name);
      const label = name;
      if (!isSystemField.success) {
        calEventUserFieldsResponses[name] = {
          label,
          value
        };
      }
      calEventResponses[name] = {
        label,
        value
      };
    }
  }
  return { userFieldsResponses: calEventUserFieldsResponses, responses: calEventResponses };
};
exports.bookingResponsesDbSchema = bookingResponsesDbSchema;
exports.getBookingResponsesSchema = getBookingResponsesSchema;
exports.getCalEventResponses = getCalEventResponses;
