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

export const createAnalysisGroup = async (analysisGroup: {
  id: string;
  name: string;
  order: number;
}) => {
  const { data: insertedAnalysisGroup, error } =
    await getSupabaseServerAdminClient()
      .schema('medreport')
      .from('analysis_groups')
      .upsert(
        {
          original_id: analysisGroup.id,
          name: analysisGroup.name,
          order: analysisGroup.order,
        },
        { onConflict: 'original_id', ignoreDuplicates: false },
      )
      .select('id');
  const analysisGroupId = insertedAnalysisGroup?.[0]?.id as number;

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

  return analysisGroupId;
};

export const getAnalysisGroups = async () => {
  const { data: analysisGroups } = await getSupabaseServerAdminClient()
    .schema('medreport')
    .from('analysis_groups')
    .select('*');

  return analysisGroups;
};
