import {updateAssetsByMessage} from '@modules/chats/db';
import {Asset, Message} from '@modules/chats/interfaces';
import {updateAssets} from '@modules/chats/store/zustand/useGroups';
import {sentryLogs} from '@shared/utils';

import {fileHandler, ProcessAttachmentParamItem} from '../FileHandler';
import {PendingAssets} from '../PendingAssets';

class AssetsServiceClass {
  processAttachments(messages: Message[]) {
    const processAssetsData: ProcessAttachmentParamItem[] = [];

    for (const message of messages) {
      if (message.attachments?.length) {
        processAssetsData.push({
          attachments: message.attachments,
          messageId: message.client_msg_id,
          messageMetadata: {
            hidden: message.hidden,
            channel: message.channel,
          },
        });
      }
      PendingAssets.addOrRemoveFromMessage(message);
    }

    if (processAssetsData.length) {
      fileHandler.processAttachmentsBatch(processAssetsData);
    }
  }

  updateAssets({
    assets,
    messageId,
    channelId,
    hidden,
    enableProcessingAssets = true,
  }: {
    assets: Asset[];
    messageId: string;
    channelId: string;
    hidden: boolean;
    enableProcessingAssets?: boolean;
  }) {
    if (!assets.length) {
      return;
    }
    try {
      updateAssetsByMessage(assets, messageId).catch(error => {
        sentryLogs.error({
          message: 'Error updating assets',
          module: 'FILES',
          data: {
            error: error instanceof Error ? error.message : String(error),
          },
        });
      });
      updateAssets({assets, messageId, channelId});
      if (enableProcessingAssets) {
        fileHandler.processAttachmentsBatch([
          {
            attachments: assets,
            messageId: messageId,
            messageMetadata: {
              hidden: hidden || false,
              channel: channelId,
            },
          },
        ]);
      }
    } catch (error) {
      sentryLogs.error({
        message: 'Error updating assets',
        module: 'FILES',
        data: {
          error: error instanceof Error ? error.message : String(error),
        },
      });
    }
  }
}

export const AssetsUpdaterService = new AssetsServiceClass();
