'use server';

import { createServerActionClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { revalidatePath } from 'next/cache';

export async function saveTasting(data: {
    bottle_id: string;
    rating: number;
    nose_notes?: string;
    palate_notes?: string;
    finish_notes?: string;
    is_sample?: boolean;
}) {
    const supabase = createServerActionClient({ cookies });

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

        const { data: tasting, error } = await supabase
            .from('tastings')
            .insert({
                bottle_id: data.bottle_id,
                user_id: session.user.id,
                rating: data.rating,
                nose_notes: data.nose_notes,
                palate_notes: data.palate_notes,
                finish_notes: data.finish_notes,
                is_sample: data.is_sample || false,
            })
            .select()
            .single();

        if (error) throw error;

        revalidatePath(`/bottles/${data.bottle_id}`);

        return { success: true, data: tasting };
    } catch (error) {
        console.error('Save Tasting Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Fehler beim Speichern der Tasting Note',
        };
    }
}
