import { readPrivateMessageResponse } from '~/lib/services/medipost/medipostPrivateMessage.service';

type ProcessedMessage = {
  messageId: string;
  hasAnalysisResponse: boolean;
  hasPartialAnalysisResponse: boolean;
  hasFullAnalysisResponse: boolean;
  medusaOrderId: string | undefined;
  analysisOrderId: number | undefined;
};

type GroupedResults = {
  processed: Pick<ProcessedMessage, 'messageId' | 'analysisOrderId'>[];
  waitingForResults: Pick<ProcessedMessage, 'messageId' | 'analysisOrderId'>[];
};

export default async function syncAnalysisResults() {
  console.info('Syncing analysis results');

  const processedMessages: ProcessedMessage[] = [];
  const excludedMessageIds: string[] = [];
  while (true) {
    const result = await readPrivateMessageResponse({ excludedMessageIds });
    if (result.messageId) {
      processedMessages.push(result as ProcessedMessage);
    }

    if (!result.messageId) {
      console.info('No more messages to process');
      break;
    }

    if (!excludedMessageIds.includes(result.messageId)) {
      excludedMessageIds.push(result.messageId);
    } else {
      break;
    }
  }

  const groupedResults = processedMessages.reduce((acc, result) => {
    if (result.analysisOrderId) {
      if (result.hasAnalysisResponse) {
        if (!acc.processed) {
          acc.processed = [];
        }
        acc.processed.push({
          messageId: result.messageId,
          analysisOrderId: result.analysisOrderId,
        });
      } else {
        if (!acc.waitingForResults) {
          acc.waitingForResults = [];
        }
        acc.waitingForResults.push({
          messageId: result.messageId,
          analysisOrderId: result.analysisOrderId,
        });
      }
    }
    return acc;
  }, {} as GroupedResults);
  console.info(
    `Processed ${processedMessages.length} messages, results: ${JSON.stringify(groupedResults)}`,
  );
}
