"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const z = require("zod");
const index = require("./index-QSf6WJj0.cjs");
const credential = require("./credential-afgv3289.cjs");
const indexBrowser = require("./index-browser-RtwB1hqI.cjs");
const CrmService = require("./CrmService-V3r_zfPn.cjs");
const sendPayload = require("./sendPayload-UqEOpTQL.cjs");
const log = index.logger.getSubLogger({ prefix: ["incomplete-booking: salesforce"] });
const incompleteBookingAction = async (action, email) => {
  const dataParse = indexBrowser.routingFormIncompleteBookingDataSchema.safeParse(action.data);
  if (!dataParse.success) {
    log.error(`Incomplete booking action data is not valid: ${dataParse.error}`);
    return;
  }
  const { writeToRecordObject } = dataParse.data;
  const credential$1 = await credential.CredentialRepository.findFirstByIdWithKeyAndUser({ id: action.credentialId });
  if (!credential$1) {
    log.error(`Credential with id ${action.credentialId} not found`);
    return;
  }
  if (writeToRecordObject) {
    const crm = new CrmService.default(credential$1, {});
    await crm.incompleteBookingWriteToRecord(email, writeToRecordObject);
  }
  return;
};
const incompleteBookingActionFunctions = {
  [index.IncompleteBookingActionType.SALESFORCE]: incompleteBookingAction
};
const incompleteBookingActionFunctions$1 = incompleteBookingActionFunctions;
const ZTriggerFormSubmittedNoEventWebhookPayloadSchema = z.z.object({
  webhook: z.z.object({
    subscriberUrl: z.z.string().url(),
    appId: z.z.string().nullable(),
    payloadTemplate: z.z.string().nullable(),
    secret: z.z.string().nullable()
  }),
  responseId: z.z.number(),
  responses: z.z.any(),
  redirect: z.z.object({
    type: z.z.enum(["customPageMessage", "externalRedirectUrl", "eventTypeRedirectUrl"]),
    value: z.z.string()
  }).optional(),
  form: z.z.object({
    id: z.z.string(),
    name: z.z.string(),
    teamId: z.z.number().nullable()
  })
});
async function triggerFormSubmittedNoEventWebhook(payload) {
  const { webhook, responseId, form, redirect, responses } = ZTriggerFormSubmittedNoEventWebhookPayloadSchema.parse(JSON.parse(payload));
  const bookingFromResponse = await index.prisma.booking.findFirst({
    where: {
      routedFromRoutingFormReponse: {
        id: responseId
      }
    }
  });
  if (bookingFromResponse) {
    return;
  }
  const sixtyMinutesAgo = new Date(Date.now() - 60 * 60 * 1e3);
  const recentResponses = await index.prisma.app_RoutingForms_FormResponse.findMany({
    where: {
      formId: form.id,
      createdAt: {
        gte: sixtyMinutesAgo,
        lt: /* @__PURE__ */ new Date()
      },
      routedToBookingUid: {
        not: null
      },
      NOT: {
        id: responseId
      }
    }
  }) ?? [];
  const emailValue = Object.values(responses).find(
    (response) => {
      const value = typeof response === "object" && response && "value" in response ? response.value : response;
      return typeof value === "string" && value.includes("@");
    }
  )?.value;
  const hasDuplicate = emailValue && recentResponses.some((response) => {
    return Object.values(response.response).some(
      (field) => {
        if (!response.response || typeof response.response !== "object")
          return false;
        return typeof field.value === "string" && field.value.toLowerCase() === emailValue.toLowerCase();
      }
    );
  });
  if (hasDuplicate) {
    return;
  }
  await sendPayload.sendGenericWebhookPayload({
    secretKey: webhook.secret,
    triggerEvent: "FORM_SUBMITTED_NO_EVENT",
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    webhook,
    data: {
      formId: form.id,
      formName: form.name,
      teamId: form.teamId,
      redirect,
      responseId,
      responses
    }
  }).catch((e) => {
    console.error(`Error executing FORM_SUBMITTED_NO_EVENT webhook`, webhook, e);
  });
  const incompleteBookingActions = await index.prisma.app_RoutingForms_IncompleteBookingActions.findMany({
    where: {
      formId: form.id
    }
  });
  if (incompleteBookingActions) {
    for (const incompleteBookingAction2 of incompleteBookingActions) {
      const actionType = incompleteBookingAction2.actionType;
      const bookingActionFunction = incompleteBookingActionFunctions$1[actionType];
      if (emailValue) {
        await bookingActionFunction(incompleteBookingAction2, emailValue);
      }
    }
  }
}
exports.ZTriggerFormSubmittedNoEventWebhookPayloadSchema = ZTriggerFormSubmittedNoEventWebhookPayloadSchema;
exports.triggerFormSubmittedNoEventWebhook = triggerFormSubmittedNoEventWebhook;
