import {
  Attachment,
  AttachmentType,
  RequestAttachment,
} from '@interfaces/attachments';
import {isInlineAudioAttachment, sizeToBytes} from '@shared/utils';

export const parsePostAttachments = (postAttachments: RequestAttachment[]) =>
  postAttachments.reduce<{
    multimedia: RequestAttachment[];
    files: RequestAttachment[];
    /** Inline audio only — for `FilesCarousel` / `PostAudioCard`. */
    audio: Attachment[];
    attachmentsSize: number;
  }>(
    (acc, attachment) => {
      if (
        attachment.type === AttachmentType.IMAGE ||
        attachment.type === AttachmentType.VIDEO
      ) {
        acc.multimedia.push(attachment);
      } else if (attachment.type === AttachmentType.FILE) {
        if (isInlineAudioAttachment(attachment)) {
          acc.audio.push(attachment as Attachment);
        }
        acc.files.push(attachment);
      } else if (attachment.type === AttachmentType.AUDIO) {
        acc.audio.push(attachment as Attachment);
        acc.files.push(attachment);
      }

      const attachmentsSize =
        acc.attachmentsSize +
        (attachment.bytes || sizeToBytes(attachment.size));

      return {...acc, attachmentsSize};
    },
    {multimedia: [], files: [], audio: [], attachmentsSize: 0},
  );
