import get from 'lodash/get';
import { DEVICE_SUPPORTED } from './constants';
import { IOS, ANDROID } from '../CreativesContainer/constants';

export const getCtaObject = (ctaData) =>
  ctaData?.map((cta, index) => {
    const { type = "", actionText = "", actionLink = "" } = cta;
    const obj = {
      index,
      text: actionText,
      url: actionLink,
      urlType: type,
      isSaved: true,
    };
    return obj;
  });

// Helper functions to check for errors
/**
 * Checks if a platform-specific error group (like STANDARD_ERROR_MSG or LIQUID_ERROR_MSG)
 * contains any errors for ANDROID, IOS, or GENERIC platforms.
 *
 * @param {object} platformErrorGroup - The error group object (e.g., errorMessage.STANDARD_ERROR_MSG).
 * @returns {boolean} True if any platform has errors, false otherwise.
 */
export const hasPlatformErrors = (platformErrorGroup) => {
  if (!platformErrorGroup) {
    return false;
  }
  return (
    platformErrorGroup.ANDROID?.length > 0
    || platformErrorGroup.IOS?.length > 0
    || platformErrorGroup.GENERIC?.length > 0
  );
};


/**
   * Checks the main errorMessage object for any standard or liquid errors
   * across all supported platforms.
   *
   * @param {object} errorMessage - The main error object.
   * @returns {boolean} True if any errors are present, false otherwise.
   */
export const hasAnyErrors = (errorMessage) => {
  if (!errorMessage) {
    return false;
  }
  return (
    hasPlatformErrors(errorMessage.STANDARD_ERROR_MSG)
    || hasPlatformErrors(errorMessage.LIQUID_ERROR_MSG)
  );
};

/**
 * Returns the single tab to be validated based on the account data.
 * @param {object} accountData - The account data.
 * @returns {string} The single tab to be validated.
 */
export const getSingleTab = (accountData) => {
  const { android, ios } = get(accountData, 'selectedWeChatAccount.configs', {});
  const androidSupported = android === DEVICE_SUPPORTED;
  const iosSupported = ios === DEVICE_SUPPORTED;

  if (androidSupported && iosSupported) return null;
  if (androidSupported) return ANDROID;
  if (iosSupported) return IOS;
  return null;
};
