const ERRORS = [
  {
    pattern: 'Video with this [(video.name or mataData.refID) and video.ownerId] already exist',
    message: 'A video with this name already exists. Rename the video in order to save it',
  },
  {
    pattern: 'Validation errors. device: size must be between 1 and 2147483647',
    message: 'Please select one of the available device types you wish to target',
  },
  {
    pattern: 'Label with this [label.name and label.contentOwnerId] already exist.',
    message: 'The custom category with the name "[categoryName]" already exists. Please use another name',
    useReplaceMetaObjectKey: 'categoryName',
  },
  {
    pattern: '"image" is not allowed to be empty',
    message: 'Image cannot be empty',
  },
  {
    pattern: "Duplicate value '1'''. Value must be unique.",
    message: 'An X-Ray Creative with this name already exists. Rename X-Ray Creative name in order to save it',
  },
];

export const mapApiError = (replaceMetaObject: { [key: string]: string }) => (errorsFromApi: string[]) => {
  const mappedError = ERRORS.find((errorForMap) =>
    errorsFromApi.some((error) => error.startsWith(errorForMap.pattern)),
  );

  if (mappedError) {
    const message = mappedError?.useReplaceMetaObjectKey
      ? mappedError.message.replace(
          `[${mappedError.useReplaceMetaObjectKey}]`,
          replaceMetaObject[mappedError.useReplaceMetaObjectKey],
        )
      : mappedError.message;
    return message;
  }

  return errorsFromApi;
};

export default ERRORS;
