'use server';

import { createClient } from '@/lib/supabase/server';
import { revalidatePath } from 'next/cache';

export async function deleteBottle(bottleId: string) {
    const supabase = await createClient();

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

        // 1. Get bottle to check ownership and get image path
        const { data: bottle, error: fetchError } = await supabase
            .from('bottles')
            .select('image_url, user_id')
            .eq('id', bottleId)
            .single();

        if (fetchError || !bottle) {
            throw new Error('Flasche nicht gefunden.');
        }

        if (bottle.user_id !== user.id) {
            throw new Error('Keine Berechtigung.');
        }

        // 2. Delete bottle (Storage image cleanup could be added here, but RLS/Storage management is easier via DB trigger or manual cleanup)
        const { error: deleteError } = await supabase
            .from('bottles')
            .delete()
            .eq('id', bottleId);

        if (deleteError) throw deleteError;

        revalidatePath('/');
        return { success: true };
    } catch (error) {
        console.error('Delete Bottle Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Fehler beim Löschen.',
        };
    }
}
