import { getSupabaseClient } from '@/lib/supabase';
import type {
  ProcurementDictionaryCreatePayload,
  ProcurementDictionaryEntry,
  ProcurementDictionaryUpdatePayload,
} from '@/types';

const TABLE = 'procurement_dictionary_entries';

export async function fetchProcurementDictionaryEntries(): Promise<ProcurementDictionaryEntry[]> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .select('*')
    .order('updated_at', { ascending: false });

  if (error) throw error;
  return data ?? [];
}

export async function createProcurementDictionaryEntry(
  payload: ProcurementDictionaryCreatePayload,
  createdBy?: string,
): Promise<ProcurementDictionaryEntry> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .insert({
      term: payload.term.trim(),
      term_type: payload.term_type,
      product_context: payload.product_context?.trim() ?? '',
      interpretation: payload.interpretation.trim(),
      suggested_keyword: payload.suggested_keyword?.trim() ?? '',
      evidence: payload.evidence?.trim() ?? '',
      note: payload.note?.trim() ?? null,
      created_by: createdBy ?? null,
    })
    .select()
    .single();

  if (error) throw error;
  return data;
}

export async function updateProcurementDictionaryEntry(
  id: string,
  payload: ProcurementDictionaryUpdatePayload,
): Promise<ProcurementDictionaryEntry> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .update({
      ...payload,
      ...(payload.term !== undefined && { term: payload.term.trim() }),
      ...(payload.product_context !== undefined && { product_context: payload.product_context.trim() }),
      ...(payload.interpretation !== undefined && { interpretation: payload.interpretation.trim() }),
      ...(payload.suggested_keyword !== undefined && { suggested_keyword: payload.suggested_keyword.trim() }),
      ...(payload.evidence !== undefined && { evidence: payload.evidence.trim() }),
      ...(payload.note !== undefined && { note: payload.note.trim() || null }),
      updated_at: new Date().toISOString(),
    })
    .eq('id', id)
    .select()
    .single();

  if (error) throw error;
  return data;
}

export async function deleteProcurementDictionaryEntry(id: string): Promise<void> {
  const supabase = getSupabaseClient();
  const { error } = await supabase
    .from(TABLE)
    .delete()
    .eq('id', id);

  if (error) throw error;
}
