import {
  WEBPUSH,
  WEBPUSH_MEDIA_TYPES,
  IMAGE_UPLOAD_METHODS,
  BRAND_ICON_OPTIONS,
  ON_CLICK_BEHAVIOUR_OPTIONS,
  ACTION_TYPES,
} from '../../constants';

/**
 * Creates the payload structure for Web Push template creation/editing
 * @param {Object} params - All parameters needed to build the payload
 * @returns {Object} The formatted Web Push payload
 */
export const createWebPushPayload = ({
  templateName,
  notificationTitle,
  message,
  mediaType,
  accountId,
  isFullMode,
  imageSrc,
  imageUrl,
  imageUploadMethod,
  brandIconOption,
  brandIconSrc,
  brandIconUrl,
  buttons,
  onClickBehaviour,
  redirectUrl,
  websiteLink
}) => {
  const trimmedTemplateName = (templateName || '').trim();
  const trimmedTitle = (notificationTitle || '').trim();
  const trimmedMessage = (message || '').trim();

  const webpushContent = {
    title: trimmedTitle,
    message: trimmedMessage,
    ...(mediaType && mediaType !== WEBPUSH_MEDIA_TYPES.NONE ? { mediaType } : {}),
  };

  // Add image data if media type is IMAGE
  if (mediaType === WEBPUSH_MEDIA_TYPES.IMAGE) {
    if (imageUploadMethod === IMAGE_UPLOAD_METHODS.UPLOAD_IMAGE && imageSrc) {
      webpushContent.image = imageSrc;
    } else if (imageUploadMethod === IMAGE_UPLOAD_METHODS.ADD_IMAGE_URL && imageSrc) {
      // Use imageSrc (uploaded secure_file_path) instead of imageUrl
      // NOTE: To move upload to save event, check imageUrl exists but imageSrc is empty, upload, then use secure_file_path
      webpushContent.image = imageSrc;
    }
  }

  // Add brand icon data if option is not DONT_SHOW
  if (brandIconOption !== BRAND_ICON_OPTIONS.DONT_SHOW && brandIconSrc) {
    webpushContent.brandIcon = brandIconSrc;
  }

  // Add on-click behaviour for the notification body
  if (onClickBehaviour === ON_CLICK_BEHAVIOUR_OPTIONS.REDIRECT_TO_URL && redirectUrl) {
    webpushContent.onClickAction = {
      type: ACTION_TYPES.URL,
      url: redirectUrl.trim(),
    };
  } else if (onClickBehaviour === ON_CLICK_BEHAVIOUR_OPTIONS.SITE_URL) {
    webpushContent.onClickAction = {
      type: ACTION_TYPES.SITE_URL,
      url: websiteLink,
    };
  }

  // Add CTA buttons if any exist
  if (buttons?.length > 0) {
    webpushContent.ctas = buttons.map((button) => ({
      actionText: button.text,
      type: ACTION_TYPES.URL,
      actionLink: button.url,
    }));
  }

  return {
    name: (isFullMode ? trimmedTemplateName : trimmedTitle) || trimmedTitle,
    type: WEBPUSH,
    definition: {
      accountId,
    },
    versions: {
      base: {
        content: {
          webpush: webpushContent,
        },
      },
    },
  };
};

