import { z } from "zod";
import { l as logger, ad as routingFormIncompleteBookingDataSchema, ae as IncompleteBookingActionType, p as prisma } from "./orgDomains-eTg-cjth.js";
import { C as CredentialRepository } from "./credential-INULiwKH.js";
import SalesforceCRMService from "./CrmService-cv08pJhj.js";
import { a as sendGenericWebhookPayload } from "./sendPayload-09zT5Q-M.js";
const log = logger.getSubLogger({ prefix: ["incomplete-booking: salesforce"] });
const incompleteBookingAction = async (action, email) => {
  const dataParse = 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 = await CredentialRepository.findFirstByIdWithKeyAndUser({ id: action.credentialId });
  if (!credential) {
    log.error(`Credential with id ${action.credentialId} not found`);
    return;
  }
  if (writeToRecordObject) {
    const crm = new SalesforceCRMService(credential, {});
    await crm.incompleteBookingWriteToRecord(email, writeToRecordObject);
  }
  return;
};
const incompleteBookingActionFunctions = {
  [IncompleteBookingActionType.SALESFORCE]: incompleteBookingAction
};
const incompleteBookingActionFunctions$1 = incompleteBookingActionFunctions;
const ZTriggerFormSubmittedNoEventWebhookPayloadSchema = z.object({
  webhook: z.object({
    subscriberUrl: z.string().url(),
    appId: z.string().nullable(),
    payloadTemplate: z.string().nullable(),
    secret: z.string().nullable()
  }),
  responseId: z.number(),
  responses: z.any(),
  redirect: z.object({
    type: z.enum(["customPageMessage", "externalRedirectUrl", "eventTypeRedirectUrl"]),
    value: z.string()
  }).optional(),
  form: z.object({
    id: z.string(),
    name: z.string(),
    teamId: z.number().nullable()
  })
});
async function triggerFormSubmittedNoEventWebhook(payload) {
  const { webhook, responseId, form, redirect, responses } = ZTriggerFormSubmittedNoEventWebhookPayloadSchema.parse(JSON.parse(payload));
  const bookingFromResponse = await prisma.booking.findFirst({
    where: {
      routedFromRoutingFormReponse: {
        id: responseId
      }
    }
  });
  if (bookingFromResponse) {
    return;
  }
  const sixtyMinutesAgo = new Date(Date.now() - 60 * 60 * 1e3);
  const recentResponses = await 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 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 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);
      }
    }
  }
}
export {
  ZTriggerFormSubmittedNoEventWebhookPayloadSchema,
  triggerFormSubmittedNoEventWebhook
};
