'use server';

import { createClient } from '@/lib/supabase/server';
import { BuddySchema, BuddyData } from '@/types/whisky';

export async function addBuddy(rawData: BuddyData) {
    const supabase = await createClient();

    try {
        const { name } = BuddySchema.parse(rawData);
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) throw new Error('Nicht autorisiert');

        const { data, error } = await supabase
            .from('buddies')
            .insert([{ name, user_id: user.id }])
            .select()
            .single();

        if (error) throw error;
        return { success: true, data };
    } catch (error) {
        console.error('Add Buddy Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Fehler beim Hinzufügen des Buddies',
        };
    }
}

export async function deleteBuddy(id: string) {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) throw new Error('Nicht autorisiert');

        const { error } = await supabase
            .from('buddies')
            .delete()
            .eq('id', id)
            .eq('user_id', user.id);

        if (error) throw error;
        return { success: true };
    } catch (error) {
        console.error('Delete Buddy Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Fehler beim Löschen des Buddies',
        };
    }
}
