/*
 * @description - format library data, for update request
 * @param values - LibraryValues, values from form.
 * @param library - Article, original library data.
 * @return - LibraryData, filled with values.
 */
import { isEqual, pick } from 'lodash-es';

import { DEFAULT_IMAGE_ICON_URL } from 'src/constants/env';
import { type SortableAttachment } from 'src/types/attachments';
import { IconTypes } from 'src/types/icons';
import {
  type Article,
  type LibraryData,
  type LibraryValues,
} from 'src/types/libraries';
import { preprocessImage } from 'src/utils/files';
import { formatOutgoingIcon } from 'src/utils/icons';

export const formatLibraryAttachmentData = (
  attachment: SortableAttachment,
  index: number,
) => {
  return {
    ...attachment,
    id: attachment.id >= 0 ? attachment.id : undefined,
    position: index,
  };
};

export const formatLibraryData = async (
  values: LibraryValues,
  library: Article,
): Promise<LibraryData> => {
  const { icon, showCoverPicture, coverPicture, attachments, ...rest } = values;

  const formattedAttachments = attachments.map(formatLibraryAttachmentData);

  return {
    ...rest,
    icon: formatOutgoingIcon(icon),
    coverPictureUrl: showCoverPicture
      ? await preprocessImage(coverPicture)
      : undefined,
    removeCoverPicture: !showCoverPicture,
    attachments: formattedAttachments,
    replaceAttachments: !isEqual(attachments, library.attachments),
  };
};

/*
 * @description - gets empty library default values, for form
 * @return - LibraryValues object, filled with default data.
 */
export const getLibraryDefaultValues = (): LibraryValues =>
  ({
    id: '',
    title: '',
    body: '',
    icon: {
      type: IconTypes.IMAGE,
      value: DEFAULT_IMAGE_ICON_URL,
    },
    coverPicture: {
      url: null,
      file: null,
    },
    showCoverPicture: false,
    attachments: [],
  }) as const;

/*
 * @description - format library default values, for form
 * @param library - library object
 * @return - LibraryValues object, filled with library data.
 */
export const formatLibraryDefaultValues = (library: Article) => {
  const defaultValues = getLibraryDefaultValues();

  if (!library) return defaultValues;

  const values = pick(library, [
    'id',
    'title',
    'body',
    'icon',
    'coverPicture',
    'attachments',
  ]);

  return {
    ...defaultValues,
    ...values,
    coverPicture: values.coverPicture
      ? { url: values.coverPicture, file: null }
      : undefined,
    showCoverPicture: !!values.coverPicture,
  };
};
