import { supabase } from '@/lib/supabase';
import { Character } from './schema';

export async function getCharacters() {
    const { data, error } = await supabase
        .from('characters')
        .select('*')
        .order('created_at', { ascending: false });

    if (error) {
        throw error;
    }

    // Optimize: validate schema? For now trust Supabase or partial validate
    return data as Character[];
}

export async function createCharacter(character: Omit<Character, 'id' | 'created_at' | 'updated_at'>) {
    const { data, error } = await supabase
        .from('characters')
        .insert(character);

    if (error) {
        throw error;
    }

    return data;
}

export async function updateCharacter(character: Character) {
    const { id, ...updates } = character;
    if (!id) throw new Error('ID is required for update');

    const { data, error } = await supabase
        .from('characters')
        .update(updates)
        .eq('id', id);

    if (error) {
        throw error;
    }

    return data;
}

export async function deleteCharacter(id: string) {
    const { error } = await supabase
        .from('characters')
        .delete()
        .eq('id', id);

    if (error) {
        throw error;
    }
}
