import React from 'react';
import { FormattedMessage } from 'react-intl';
import { ANDROID, GENERIC, IOS } from '../../v2Containers/CreativesContainer/constants';

export const processErrors = (rawErrorData, errorType, platform, messages) => {
  let errorsToShow = [];
  let titleMsg = messages.standardErrorHeader;
  let platformLabel = null;

  const isObject = typeof rawErrorData === 'object' && rawErrorData !== null;
  const isNotArray = !Array.isArray(rawErrorData);
  const hasPlatformKeys = isObject && isNotArray && [ANDROID, IOS, GENERIC].some((key) => key in rawErrorData);
  if (hasPlatformKeys) {
    if (errorType === "liquid") {
      titleMsg = messages.dynamicErrorHeader;
    }
    errorsToShow = rawErrorData[platform] || [];
    platformLabel = platform; // Only set platform label for new structure
  } else if (Array.isArray(rawErrorData)) {
    errorsToShow = rawErrorData;
    if (errorType === "liquid") {
      titleMsg = messages.dynamicErrorHeader;
    }
  }

  const title = <FormattedMessage {...titleMsg} />;
  return { errorsToShow, title, platformLabel };
};

export const getLiquidProps = (errors, isAndroid, showTitle, showPlatformLabels) => ({
  title: (isAndroid || !showTitle) && errors?.LIQUID?.title,
  errors: [
    ...(errors?.STANDARD?.errorsToShow || []),  
    ...(errors?.LIQUID?.errorsToShow || []),
  ],
  liquidError: !!errors?.LIQUID?.errorsToShow?.length,
  platformLabel: showPlatformLabels ? (isAndroid ? ANDROID : IOS) : null,
});

/**
 * Returns true if either standard or liquid errorsToShow arrays have length > 0.
 * @param {Object} errors - The error object for a platform (androidErrors or iosErrors)
 * @returns {boolean}
 */
export const hasPlatformErrors = (errors) => {
  if (!errors) return false;
  const standardLength = errors?.STANDARD?.errorsToShow?.length || 0;
  const liquidLength = errors?.LIQUID?.errorsToShow?.length || 0;
  return standardLength > 0 || liquidLength > 0;
};
