'use server';

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

import { UpdateBottleSchema, UpdateBottleData } from '@/types/whisky';

export async function updateBottle(bottleId: string, rawData: UpdateBottleData) {
    const supabase = await createClient();

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

        const { error } = await supabase
            .from('bottles')
            .update({
                name: data.name,
                distillery: data.distillery,
                category: data.category,
                abv: data.abv,
                age: data.age,
                whiskybase_id: data.whiskybase_id,
                purchase_price: data.purchase_price,
                distilled_at: data.distilled_at,
                bottled_at: data.bottled_at,
                batch_info: data.batch_info,
                cask_type: data.cask_type,
                status: data.status,
                updated_at: new Date().toISOString(),
            })
            .eq('id', bottleId)
            .eq('user_id', user.id);

        if (error) throw error;

        revalidatePath(`/bottles/${bottleId}`);
        revalidatePath('/');

        return { success: true };
    } catch (error) {
        console.error('Update Bottle Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren der Flaschendaten',
        };
    }
}
