import { getSupabaseClient } from '@/lib/supabase';
import type { ModelOverride, ModelOverrideCreatePayload, ModelOverrideUpdatePayload } from '@/types';

const TABLE = 'model_number_overrides';

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

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

export async function createModelOverride(payload: ModelOverrideCreatePayload, createdBy?: string): Promise<ModelOverride> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .insert({
      model_number: payload.model_number.trim().toUpperCase(),
      suggested_keyword: payload.suggested_keyword.trim(),
      note: payload.note?.trim() ?? null,
      created_by: createdBy ?? null,
    })
    .select()
    .single();

  if (error) throw error;
  return data;
}

export async function updateModelOverride(id: string, payload: ModelOverrideUpdatePayload): Promise<ModelOverride> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .update({
      ...payload,
      ...(payload.model_number !== undefined && { model_number: payload.model_number.trim().toUpperCase() }),
      updated_at: new Date().toISOString(),
    })
    .eq('id', id)
    .select()
    .single();

  if (error) throw error;
  return data;
}

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

  if (error) throw error;
}
