import { MessageDocument } from '../../components/UiComponents/Messages/MessagesTypes';
import type { WorkflowMessage, WorkflowLog } from '../../api/workflowApi';

export const sortMessages = (a: WorkflowMessage, b: WorkflowMessage) => {
  if (a.publishedAt !== undefined && b.publishedAt !== undefined) {
    return a.publishedAt - b.publishedAt;
  }
  if (a.publishedAt !== undefined) return -1;
  if (b.publishedAt !== undefined) return 1;
  if (a.sequenceNr !== undefined && b.sequenceNr !== undefined) {
    return a.sequenceNr - b.sequenceNr;
  }
  return 0;
};

export const sortLogs = (a: WorkflowLog, b: WorkflowLog) => {
  if (a.timestamp !== undefined && b.timestamp !== undefined) {
    return a.timestamp - b.timestamp;
  }
  if (a.publishedAt !== undefined && b.publishedAt !== undefined) {
    return a.publishedAt - b.publishedAt;
  }
  if (a.sequenceNr !== undefined && b.sequenceNr !== undefined) {
    return a.sequenceNr - b.sequenceNr;
  }
  return 0;
};

export const extractFileIdsFromMessage = (message: WorkflowMessage): Set<string> => {
  const fileIds = new Set<string>();
  const documents = (message as any).documents as MessageDocument[] | undefined;
  const files = (message as any).files as any[] | undefined;
  
  if (documents && Array.isArray(documents)) {
    documents.forEach((doc: MessageDocument) => {
      if (doc.fileId) fileIds.add(doc.fileId);
    });
  }
  if (files && Array.isArray(files)) {
    files.forEach((file: any) => {
      const fileId = file.id || file.fileId;
      if (fileId) fileIds.add(fileId);
    });
  }
  return fileIds;
};

export const convertFilesToDocuments = (files: any[], messageId: string): MessageDocument[] => {
  return files.map((file: any) => ({
    id: file.id || file.fileId || file.file_id,
    fileId: file.id || file.fileId || file.file_id,
    fileName: file.fileName || file.name || file.file_name || 'Unknown File',
    fileSize: file.fileSize || file.size || 0,
    mimeType: file.mimeType || file.mime_type || 'application/octet-stream',
    messageId,
    roundNumber: 0,
    taskNumber: 0,
    actionNumber: 0,
    actionId: ''
  }));
};

