import { AnalysisOrderStatus } from '@/packages/shared/src/types/medipost-analysis';
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';

import type { AnalysisResponseElement } from '../types/analysis-response-element';

export async function getExistingAnalysisResponseElements({
  analysisResponseId,
}: {
  analysisResponseId: number;
}): Promise<AnalysisResponseElement[]> {
  const { data } = await getSupabaseServerAdminClient()
    .schema('medreport')
    .from('analysis_response_elements')
    .select('*')
    .eq('analysis_response_id', analysisResponseId)
    .throwOnError();

  return data as AnalysisResponseElement[];
}

export async function upsertAnalysisResponseElement({
  element,
}: {
  element: Omit<AnalysisResponseElement, 'created_at' | 'updated_at' | 'id'>;
}) {
  const { data } = await getSupabaseServerAdminClient()
    .schema('medreport')
    .from('analysis_response_elements')
    .upsert(element, {
      onConflict: 'analysis_response_id,analysis_element_original_id',
      ignoreDuplicates: false,
    })
    .select('id')
    .throwOnError();

  const analysisResponseElementId = data?.[0]?.id;
  if (!analysisResponseElementId) {
    throw new Error(
      `Failed to insert or update analysis response element (response id: ${element.analysis_response_id}, element id: ${element.analysis_element_original_id})`,
    );
  }

  return { analysisResponseElementId };
}

export async function upsertAnalysisResponse({
  analysisOrderId,
  orderNumber,
  orderStatus,
  userId,
}: {
  analysisOrderId: number;
  orderNumber: string;
  orderStatus: (typeof AnalysisOrderStatus)[keyof typeof AnalysisOrderStatus];
  userId: string;
}) {
  const { data: analysisResponse } = await getSupabaseServerAdminClient()
    .schema('medreport')
    .from('analysis_responses')
    .upsert(
      {
        analysis_order_id: analysisOrderId,
        order_number: orderNumber,
        order_status: orderStatus,
        user_id: userId,
      },
      { onConflict: 'order_number', ignoreDuplicates: false },
    )
    .select('id')
    .throwOnError();

  const analysisResponseId = analysisResponse?.[0]?.id;
  if (!analysisResponseId) {
    throw new Error(
      `Failed to insert or update analysis order response (order id: ${analysisOrderId}, order number: ${orderNumber})`,
    );
  }

  return { analysisResponseId };
}
