"use strict";
const CalEventParser = require("./CalEventParser-RR7nWuhu.cjs");
const index = require("./i18n-HHdcQbuJ.cjs");
const index$1 = require("./email-manager-NqFEofh9.cjs");
const user = require("./user-xjV81VA_.cjs");
const fieldsThatSupportLabelAsSafeHtml = ["boolean", "radio"];
const getFieldIdentifier = (name) => {
  return index.getValidRhfFieldName(name);
};
if (typeof window !== "undefined" && !process.env.INTEGRATION_TEST_MODE) {
  throw new Error("`getBookingFields` must not be imported on the client side.");
}
function upperCaseToCamelCase(upperCaseString) {
  return upperCaseString[0].toUpperCase() + upperCaseString.slice(1).toLowerCase();
}
const getSmsReminderNumberField = () => ({
  name: CalEventParser.SMS_REMINDER_NUMBER_FIELD,
  type: "phone",
  defaultLabel: "number_text_notifications",
  defaultPlaceholder: "enter_phone_number",
  editable: "system"
});
const getSmsReminderNumberSource = ({
  workflowId,
  isSmsReminderNumberRequired
}) => ({
  id: `${workflowId}`,
  type: "workflow",
  label: "Workflow",
  fieldRequired: isSmsReminderNumberRequired,
  editUrl: `/workflows/${workflowId}`
});
const getAIAgentCallPhoneNumberField = () => ({
  name: CalEventParser.CAL_AI_AGENT_PHONE_NUMBER_FIELD,
  type: "phone",
  defaultLabel: "phone_number_for_ai_call",
  defaultPlaceholder: "enter_phone_number",
  editable: "system"
});
const getAIAgentCallPhoneNumberSource = ({
  workflowId,
  isAIAgentCallPhoneNumberRequired
}) => ({
  id: `${workflowId}`,
  type: "workflow",
  label: "Workflow",
  fieldRequired: isAIAgentCallPhoneNumberRequired,
  editUrl: `/workflows/${workflowId}`
});
const getBookingFieldsWithSystemFields = ({
  bookingFields,
  disableGuests,
  isOrgTeamEvent = false,
  disableBookingTitle,
  customInputs,
  metadata,
  workflows
}) => {
  const parsedMetaData = index.EventTypeMetaDataSchema.parse(metadata || {});
  const parsedBookingFields = index.eventTypeBookingFields.parse(bookingFields || []);
  const parsedCustomInputs = index.customInputSchema.array().parse(customInputs || []);
  workflows = workflows || [];
  return ensureBookingInputsHaveSystemFields({
    bookingFields: parsedBookingFields,
    disableGuests,
    isOrgTeamEvent,
    disableBookingTitle,
    additionalNotesRequired: parsedMetaData?.additionalNotesRequired || false,
    customInputs: parsedCustomInputs,
    workflows
  });
};
const ensureBookingInputsHaveSystemFields = ({
  bookingFields,
  disableGuests,
  isOrgTeamEvent,
  disableBookingTitle,
  additionalNotesRequired,
  customInputs,
  workflows
}) => {
  const hideBookingTitle = disableBookingTitle ?? true;
  const handleMigration = !bookingFields.length;
  const CustomInputTypeToFieldType = {
    [index.EventTypeCustomInputType.TEXT]: index.BookingFieldTypeEnum.text,
    [index.EventTypeCustomInputType.TEXTLONG]: index.BookingFieldTypeEnum.textarea,
    [index.EventTypeCustomInputType.NUMBER]: index.BookingFieldTypeEnum.number,
    [index.EventTypeCustomInputType.BOOL]: index.BookingFieldTypeEnum.boolean,
    [index.EventTypeCustomInputType.RADIO]: index.BookingFieldTypeEnum.radio,
    [index.EventTypeCustomInputType.PHONE]: index.BookingFieldTypeEnum.phone
  };
  const smsNumberSources = [];
  workflows.forEach((workflow) => {
    workflow.workflow.steps.forEach((step) => {
      if (step.action === "SMS_ATTENDEE" || step.action === "WHATSAPP_ATTENDEE") {
        const workflowId = workflow.workflow.id;
        smsNumberSources.push(
          getSmsReminderNumberSource({
            workflowId,
            isSmsReminderNumberRequired: !!step.numberRequired
          })
        );
      }
    });
  });
  const isEmailFieldOptional = !!bookingFields.find((field) => field.name === "email" && !field.required);
  const systemBeforeFields = [
    {
      type: "name",
      // This is the `name` of the main field
      name: "name",
      editable: "system",
      // This Label is used in Email only as of now.
      defaultLabel: "your_name",
      required: true,
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    },
    {
      defaultLabel: "email_address",
      type: "email",
      name: "email",
      required: !isEmailFieldOptional,
      editable: "system-but-optional",
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    },
    {
      defaultLabel: "phone_number",
      type: "phone",
      name: "attendeePhoneNumber",
      required: false,
      hidden: true,
      editable: "system-but-optional",
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    },
    {
      defaultLabel: "location",
      type: "radioInput",
      name: "location",
      editable: "system",
      hideWhenJustOneOption: true,
      required: false,
      getOptionsAt: "locations",
      optionsInputs: {
        attendeeInPerson: {
          type: "address",
          required: true,
          placeholder: ""
        },
        somewhereElse: {
          type: "text",
          required: true,
          placeholder: ""
        },
        phone: {
          type: "phone",
          required: true,
          placeholder: ""
        }
      },
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    }
  ];
  const systemAfterFields = [
    {
      defaultLabel: "what_is_this_meeting_about",
      type: "text",
      name: "title",
      editable: "system-but-optional",
      required: true,
      hidden: hideBookingTitle,
      defaultPlaceholder: "",
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    },
    {
      defaultLabel: "additional_notes",
      type: "textarea",
      name: "notes",
      editable: "system-but-optional",
      required: additionalNotesRequired,
      defaultPlaceholder: "share_additional_notes",
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    },
    {
      defaultLabel: "additional_guests",
      type: "multiemail",
      editable: "system-but-optional",
      name: "guests",
      defaultPlaceholder: "email",
      required: false,
      hidden: disableGuests,
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    },
    {
      defaultLabel: "reason_for_reschedule",
      type: "textarea",
      editable: "system-but-optional",
      name: "rescheduleReason",
      defaultPlaceholder: "reschedule_placeholder",
      required: false,
      views: [
        {
          id: "reschedule",
          label: "Reschedule View"
        }
      ],
      sources: [
        {
          label: "Default",
          id: "default",
          type: "default"
        }
      ]
    }
  ];
  const missingSystemBeforeFields = [];
  for (const field of systemBeforeFields) {
    const existingBookingFieldIndex = bookingFields.findIndex(
      (f) => getFieldIdentifier(f.name) === getFieldIdentifier(field.name)
    );
    if (existingBookingFieldIndex === -1) {
      missingSystemBeforeFields.push(field);
    } else {
      bookingFields[existingBookingFieldIndex] = {
        ...field,
        ...bookingFields[existingBookingFieldIndex]
      };
    }
  }
  bookingFields = missingSystemBeforeFields.concat(bookingFields);
  if (smsNumberSources.length && !bookingFields.find((f) => getFieldIdentifier(f.name) !== getFieldIdentifier(CalEventParser.SMS_REMINDER_NUMBER_FIELD))) {
    const indexForLocation = bookingFields.findIndex(
      (f) => getFieldIdentifier(f.name) === getFieldIdentifier("location")
    );
    bookingFields.splice(indexForLocation + 1, 0, {
      ...getSmsReminderNumberField(),
      sources: smsNumberSources
    });
  }
  if (handleMigration) {
    customInputs.forEach((input, index$12) => {
      const label = input.label || `${upperCaseToCamelCase(input.type)}`;
      bookingFields.push({
        label,
        editable: "user",
        // Custom Input's slugified label was being used as query param for prefilling. So, make that the name of the field
        // Also Custom Input's label could have been empty string as well. But it's not possible to have empty name. So generate a name automatically.
        name: index.slugify(input.label || `${input.type}-${index$12 + 1}`),
        placeholder: input.placeholder,
        type: CustomInputTypeToFieldType[input.type],
        required: input.required,
        options: input.options ? input.options.map((o) => {
          return {
            ...o,
            // Send the label as the value without any trimming or lowercase as this is what customInput are doing. It maintains backward compatibility
            value: o.label
          };
        }) : []
      });
    });
  }
  const missingSystemAfterFields = [];
  for (const field of systemAfterFields) {
    const existingBookingFieldIndex = bookingFields.findIndex(
      (f) => getFieldIdentifier(f.name) === getFieldIdentifier(field.name)
    );
    if (existingBookingFieldIndex === -1) {
      missingSystemAfterFields.push(field);
    } else {
      bookingFields[existingBookingFieldIndex] = {
        // Adding the fields from Code first and then fields from DB. Allows, the code to push new properties to the field
        ...field,
        ...bookingFields[existingBookingFieldIndex]
      };
    }
  }
  bookingFields = bookingFields.concat(missingSystemAfterFields).map((f) => {
    return {
      ...f,
      // TODO: This has to be a FormBuilder feature and not be specific to bookingFields. Either use zod transform in FormBuilder to add labelAsSafeHtml automatically or add a getter for fields that would do this.
      ...fieldsThatSupportLabelAsSafeHtml.includes(f.type) ? { labelAsSafeHtml: index$1.markdownToSafeHTML(f.label || null) || "" } : null
    };
  });
  return index.eventTypeBookingFields.brand().parse(bookingFields);
};
const getBrand = async (orgId) => {
  if (!orgId) {
    return null;
  }
  const org = await index.prisma.team.findUnique({
    where: {
      id: orgId
    },
    select: {
      logoUrl: true,
      name: true,
      slug: true,
      metadata: true,
      isPlatform: true
    }
  });
  if (!org) {
    return null;
  }
  if (org.isPlatform) {
    return null;
  }
  const metadata = index.teamMetadataSchema.parse(org.metadata);
  const slug = org.slug || metadata?.requestedSlug;
  const fullDomain = user.getOrgFullOrigin(slug);
  const domainSuffix = user.subdomainSuffix();
  return {
    ...org,
    metadata,
    slug,
    fullDomain,
    domainSuffix
  };
};
const getBookerBaseUrl = async (organizationId) => {
  const orgBrand = await getBrand(organizationId);
  return orgBrand?.fullDomain ?? index.WEBSITE_URL;
};
function hasFilter(filters) {
  return Object.entries(filters).some(([, filter]) => {
    return !!filter;
  });
}
exports.getAIAgentCallPhoneNumberField = getAIAgentCallPhoneNumberField;
exports.getAIAgentCallPhoneNumberSource = getAIAgentCallPhoneNumberSource;
exports.getBookerBaseUrl = getBookerBaseUrl;
exports.getBookingFieldsWithSystemFields = getBookingFieldsWithSystemFields;
exports.getSmsReminderNumberField = getSmsReminderNumberField;
exports.getSmsReminderNumberSource = getSmsReminderNumberSource;
exports.hasFilter = hasFilter;
