import * as React from "react";
function isValidEmailAddress(value) {
  const email = value.trim();
  if (!email || email.length > 254) return false;
  const atIndex = email.indexOf("@");
  if (atIndex <= 0 || atIndex !== email.lastIndexOf("@") || atIndex === email.length - 1) return false;
  for (const char of email) {
    if (char === " " || char === "	" || char === "\n" || char === "\r") return false;
  }
  const localPart = email.slice(0, atIndex);
  const domainPart = email.slice(atIndex + 1);
  if (!localPart || !domainPart || localPart.length > 64) return false;
  if (domainPart.length > 253 || !domainPart.includes(".")) return false;
  if (domainPart.startsWith(".") || domainPart.endsWith(".") || domainPart.includes("..")) return false;
  const domainLabels = domainPart.split(".");
  for (const label of domainLabels) {
    if (!label) return false;
    if (label.startsWith("-") || label.endsWith("-")) return false;
  }
  return true;
}
function mapRecipients(recipientIds) {
  return recipientIds.map((userId) => ({ userId, type: "to" }));
}
function buildComposePayload(params, input) {
  const publicMessage = params.visibility === "public";
  const sourceEntityType = params.contextObject?.sourceEntityType ?? params.defaultValues?.sourceEntityType;
  const sourceEntityId = params.contextObject?.sourceEntityId ?? params.defaultValues?.sourceEntityId;
  const selectedContextActionOption = params.contextActionOptions.find((option) => option.id === params.contextActionType);
  const resolvedContextActionRequired = params.shouldShowContextActions ? params.normalizedRequiredActionMode === "required" ? true : params.contextActionRequired : params.contextObject?.actionRequired ?? false;
  const resolvedContextActionType = resolvedContextActionRequired ? params.shouldShowContextActions ? params.contextActionType : params.contextObject?.actionType : void 0;
  const resolvedContextActionLabel = resolvedContextActionRequired ? params.shouldShowContextActions ? selectedContextActionOption?.label : params.contextObject?.actionLabel : void 0;
  const contextObjects = params.contextObject ? [{
    entityModule: params.contextObject.entityModule,
    entityType: params.contextObject.entityType,
    entityId: params.contextObject.entityId,
    actionRequired: resolvedContextActionRequired,
    actionType: resolvedContextActionType,
    actionLabel: resolvedContextActionLabel
  }] : void 0;
  return {
    type: params.messageType,
    priority: params.priority,
    visibility: params.visibility,
    externalEmail: publicMessage ? params.externalEmail.trim() : void 0,
    externalName: void 0,
    recipients: publicMessage ? [] : mapRecipients(params.recipientIds),
    subject: params.subject.trim(),
    body: params.body,
    bodyFormat: params.bodyFormat,
    sourceEntityType: sourceEntityType ?? void 0,
    sourceEntityId: sourceEntityId ?? void 0,
    objects: contextObjects,
    attachmentIds: input.attachmentIds.length > 0 ? input.attachmentIds : void 0,
    sendViaEmail: publicMessage ? true : params.sendViaEmail,
    isDraft: input.isDraft
  };
}
function useComposeSendOperation(params) {
  return React.useMemo(() => ({
    validate: () => {
      if (params.visibility !== "public" && params.recipientIds.length === 0) {
        return params.t("messages.errors.noRecipients", "Please add at least one recipient.");
      }
      if (params.visibility === "public" && !isValidEmailAddress(params.externalEmail.trim())) {
        return params.t("messages.errors.noExternalEmail", "Please enter a valid external email.");
      }
      if (!params.subject.trim()) {
        return params.t("messages.errors.noSubject", "Please enter a subject.");
      }
      if (!params.body.trim()) {
        return params.t("messages.errors.noBody", "Please enter a message.");
      }
      if (!params.createableMessageTypes.some((item) => item.type === params.messageType)) {
        return params.t("messages.errors.sendFailed", "Failed to send message.");
      }
      if (params.shouldShowContextActions && params.normalizedRequiredActionMode === "required" && !params.contextActionType) {
        return params.t("messages.composer.objectPicker.errors.actionRequired", "Select an action.");
      }
      if (params.shouldShowContextActions && params.normalizedRequiredActionMode === "optional" && params.contextActionRequired && !params.contextActionType) {
        return params.t("messages.composer.objectPicker.errors.actionRequired", "Select an action.");
      }
      return null;
    },
    buildRequest: ({ attachmentIds }) => ({
      endpoint: "/api/messages",
      method: "POST",
      payload: buildComposePayload(params, { attachmentIds, isDraft: false })
    }),
    successMessage: params.t("messages.flash.sentSuccess", "Message sent."),
    requiresAttachmentRefresh: true
  }), [params]);
}
function useComposeDraftOperation(params) {
  return React.useMemo(() => ({
    validate: () => null,
    buildRequest: ({ attachmentIds }) => {
      const payload = buildComposePayload(params, { attachmentIds, isDraft: true });
      if (!params.messageId) {
        return {
          endpoint: "/api/messages",
          method: "POST",
          payload
        };
      }
      const draftUpdatePayload = { ...payload };
      delete draftUpdatePayload.isDraft;
      return {
        endpoint: `/api/messages/${encodeURIComponent(params.messageId)}`,
        method: "PATCH",
        payload: draftUpdatePayload
      };
    },
    successMessage: params.t("messages.flash.draftSaved", "Draft saved."),
    requiresAttachmentRefresh: true
  }), [params]);
}
function useReplySubmitOperation(params) {
  return React.useMemo(() => ({
    validate: () => {
      if (!params.body.trim()) {
        return params.t("messages.errors.noBody", "Please enter a message.");
      }
      if (!params.messageId) {
        return params.t("messages.errors.invalidContext", "Message context is missing.");
      }
      return null;
    },
    buildRequest: ({ attachmentIds }) => ({
      endpoint: `/api/messages/${encodeURIComponent(params.messageId ?? "")}/reply`,
      method: "POST",
      payload: {
        body: params.body,
        bodyFormat: params.bodyFormat,
        replyAll: params.replyAll,
        recipients: params.recipientIds.length > 0 ? mapRecipients(params.recipientIds) : void 0,
        attachmentIds: attachmentIds.length > 0 ? attachmentIds : void 0,
        sendViaEmail: params.sendViaEmail
      }
    }),
    successMessage: params.t("messages.flash.replySuccess", "Reply sent."),
    requiresAttachmentRefresh: true
  }), [params]);
}
function useForwardSubmitOperation(params) {
  return React.useMemo(() => ({
    validate: () => {
      if (params.recipientIds.length === 0) {
        return params.t("messages.errors.noRecipients", "Please add at least one recipient.");
      }
      if (!params.messageId) {
        return params.t("messages.errors.invalidContext", "Message context is missing.");
      }
      if (!params.body.trim()) {
        return params.t("messages.errors.noBody", "Please enter a message.");
      }
      return null;
    },
    buildRequest: () => ({
      endpoint: `/api/messages/${encodeURIComponent(params.messageId ?? "")}/forward`,
      method: "POST",
      payload: {
        recipients: mapRecipients(params.recipientIds),
        body: params.body,
        includeAttachments: params.includeAttachments,
        sendViaEmail: params.sendViaEmail
      }
    }),
    successMessage: params.t("messages.flash.forwardSuccess", "Message forwarded."),
    requiresAttachmentRefresh: false
  }), [params]);
}
function useSendDraftOperation(params) {
  return React.useMemo(() => ({
    validate: () => {
      if (params.visibility !== "public" && params.recipientIds.length === 0) {
        return params.t("messages.errors.noRecipients", "Please add at least one recipient.");
      }
      if (params.visibility === "public" && !isValidEmailAddress(params.externalEmail.trim())) {
        return params.t("messages.errors.noExternalEmail", "Please enter a valid external email.");
      }
      if (!params.subject.trim()) {
        return params.t("messages.errors.noSubject", "Please enter a subject.");
      }
      if (!params.body.trim()) {
        return params.t("messages.errors.noBody", "Please enter a message.");
      }
      return null;
    },
    buildRequest: ({ attachmentIds }) => ({
      endpoint: `/api/messages/${encodeURIComponent(params.messageId)}`,
      method: "PATCH",
      payload: buildComposePayload(params, { attachmentIds, isDraft: false })
    }),
    successMessage: params.t("messages.flash.sentSuccess", "Message sent."),
    requiresAttachmentRefresh: true
  }), [params]);
}
function useUpdateDraftOperation(params) {
  return React.useMemo(() => ({
    validate: () => null,
    buildRequest: ({ attachmentIds }) => {
      const { isDraft: _omit, ...payload } = buildComposePayload(params, { attachmentIds, isDraft: true });
      return {
        endpoint: `/api/messages/${encodeURIComponent(params.messageId)}`,
        method: "PATCH",
        payload
      };
    },
    successMessage: params.t("messages.flash.draftSaved", "Draft saved."),
    requiresAttachmentRefresh: true
  }), [params]);
}
export {
  useComposeDraftOperation,
  useComposeSendOperation,
  useForwardSubmitOperation,
  useReplySubmitOperation,
  useSendDraftOperation,
  useUpdateDraftOperation
};
//# sourceMappingURL=useMessageComposeOperations.js.map
