import type { Tables } from '@/packages/supabase/src/database.types';

import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';

import type { IUuringElement } from './medipost/medipost.types';

export type AnalysesWithGroupsAndElements = ({
  analysis_elements: Tables<{ schema: 'medreport' }, 'analysis_elements'> & {
    analysis_groups: Tables<{ schema: 'medreport' }, 'analysis_groups'>;
  };
} & Tables<{ schema: 'medreport' }, 'analyses'>)[];

export const createAnalysis = async (
  analysis: IUuringElement,
  insertedAnalysisElementId: number,
) => {
  const { data: insertedAnalysis, error } = await getSupabaseServerAdminClient()
    .schema('medreport')
    .from('analyses')
    .upsert(
      {
        analysis_id_oid: analysis.UuringIdOID,
        analysis_id_original: analysis.UuringId,
        tehik_short_loinc: analysis.TLyhend,
        tehik_loinc_name: analysis.KNimetus,
        analysis_name_lab: analysis.UuringNimi,
        order: analysis.Jarjekord,
        parent_analysis_element_id: insertedAnalysisElementId,
      },
      { onConflict: 'analysis_id_original', ignoreDuplicates: false },
    )
    .select('id');
  const insertedAnalysisId = insertedAnalysis?.[0]?.id as number;

  if (error || !insertedAnalysisId) {
    throw new Error(
      `Failed to insert analysis (id: ${analysis.UuringId}) error: ${error?.message}`,
    );
  }

  return insertedAnalysisId;
};

const createSyncEntry = async ({
  operation,
  status,
  comment,
}: {
  operation: 'ANALYSES_SYNC' | 'ANALYSIS_GROUPS_SYNC' | 'ANALYSES_MEDUSA_SYNC';
  status: 'SUCCESS' | 'FAIL';
  comment?: string;
}) => {
  await getSupabaseServerAdminClient()
    .schema('audit')
    .from('sync_entries')
    .insert({
      operation,
      status,
      changed_by_role: 'service_role',
      comment,
    });
};

export const createNoNewDataReceivedEntry = async () => {
  await createSyncEntry({
    operation: 'ANALYSES_SYNC',
    status: 'SUCCESS',
    comment: 'No new data received',
  });
};

export const createNoDataReceivedEntry = async () => {
  await createSyncEntry({
    operation: 'ANALYSES_SYNC',
    status: 'SUCCESS',
    comment: 'No data received',
  });
};

export const createSyncFailEntry = async (error: string) => {
  await createSyncEntry({
    operation: 'ANALYSES_SYNC',
    status: 'FAIL',
    comment: error,
  });
};

export const createSyncSuccessEntry = async () => {
  await createSyncEntry({
    operation: 'ANALYSES_SYNC',
    status: 'SUCCESS',
  });
};

export const createMedusaSyncFailEntry = async (error: string) => {
  await createSyncEntry({
    operation: 'ANALYSES_MEDUSA_SYNC',
    status: 'FAIL',
    comment: error,
  });
};

export const createMedusaSyncSuccessEntry = async () => {
  await createSyncEntry({
    operation: 'ANALYSES_MEDUSA_SYNC',
    status: 'SUCCESS',
  });
};

export async function getAnalyses({
  ids,
  originalIds,
}: {
  ids?: number[];
  originalIds?: string[];
}): Promise<AnalysesWithGroupsAndElements> {
  const query = getSupabaseServerAdminClient()
    .schema('medreport')
    .from('analyses')
    .select(`*, analysis_elements(*, analysis_groups(*))`);
  if (Array.isArray(ids)) {
    query.in('id', ids);
  }
  if (Array.isArray(originalIds)) {
    query.in('analysis_id_original', originalIds);
  }
  const { data } = await query.throwOnError();

  return data as unknown as AnalysesWithGroupsAndElements;
}
