'use server';

import type { Message } from '@/lib/types/medipost';
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';

export async function getLatestMessage({
  messages,
  excludedMessageIds,
}: {
  messages?: Message[];
  excludedMessageIds?: string[];
}) {
  if (!messages?.length) {
    return null;
  }

  const filtered = messages.filter(
    ({ messageId }) => !excludedMessageIds?.includes(messageId),
  );

  if (!filtered.length) {
    return null;
  }

  return filtered.reduce(
    (prev, current) =>
      Number(prev.messageId) > Number(current.messageId) ? prev : current,
    { messageId: '' } as Message,
  );
}

export async function upsertMedipostActionLog({
  action,
  xml,
  hasAnalysisResults = false,
  medusaOrderId,
  responseXml,
  hasError = false,
  medipostExternalOrderId,
  medipostPrivateMessageId,
}: {
  action:
    | 'send_order_to_medipost'
    | 'sync_analysis_results_from_medipost'
    | 'send_fake_analysis_results_to_medipost';
  xml: string;
  hasAnalysisResults?: boolean;
  medusaOrderId?: string | null;
  responseXml?: string | null;
  hasError?: boolean;
  medipostExternalOrderId?: string | null;
  medipostPrivateMessageId?: string | null;
}) {
  const recordData = {
    action,
    xml,
    has_analysis_results: hasAnalysisResults,
    medusa_order_id: medusaOrderId,
    response_xml: responseXml,
    has_error: hasError,
    medipost_external_order_id: medipostExternalOrderId,
    medipost_private_message_id: medipostPrivateMessageId,
  };

  const query = getSupabaseServerAdminClient()
    .schema('medreport')
    .from('medipost_actions');
  const { data } = medipostPrivateMessageId
    ? await query
        .upsert(recordData, {
          onConflict: 'medipost_private_message_id',
          ignoreDuplicates: false,
        })
        .select('id')
        .throwOnError()
    : await query.insert(recordData).select('id').throwOnError();

  const medipostActionId = data?.[0]?.id;
  if (!medipostActionId) {
    throw new Error(
      `Failed to insert or update medipost action (private message id: ${medipostPrivateMessageId})`,
    );
  }

  return { medipostActionId };
}
