'use server';

import { createClient } from '@/lib/supabase/server';
import { revalidatePath } from 'next/cache';
import { validateSession } from './validate-session';

import { TastingNoteSchema, TastingNoteData } from '@/types/whisky';
import { extractFlavorProfile } from './extract-flavor-profile';

export async function saveTasting(rawData: TastingNoteData) {
    const supabase = await createClient();

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

        // Extract Tag Names for AI analysis
        let tagNames: string[] = [];
        if (data.tag_ids && data.tag_ids.length > 0) {
            const { data: tags } = await supabase
                .from('tags')
                .select('name')
                .in('id', data.tag_ids);
            if (tags) tagNames = tags.map(t => t.name);
        }

        // Generate Flavor Profile via AI
        const flavorProfile = await extractFlavorProfile(
            data.nose_notes || '',
            data.palate_notes || '',
            data.finish_notes || '',
            tagNames
        );

        // Validate Session Age (12 hour limit)
        if (data.session_id) {
            const isValid = await validateSession(data.session_id);
            if (!isValid) {
                throw new Error('Dieses Tasting Session ist bereits abgelaufen (Limit: 12 Stunden).');
            }
        }

        const { data: tasting, error: insertError } = await supabase
            .from('tastings')
            .insert({
                bottle_id: data.bottle_id,
                user_id: user.id,
                session_id: data.session_id,
                rating: data.rating,
                nose_notes: data.nose_notes,
                palate_notes: data.palate_notes,
                finish_notes: data.finish_notes,
                flavor_profile: flavorProfile,
                is_sample: data.is_sample || false,
                tasted_at: data.tasted_at || new Date().toISOString(),
                created_at: new Date().toISOString(),
                // New Blind Mode fields
                blind_label: data.blind_label,
                guess_abv: data.guess_abv,
                guess_age: data.guess_age,
                guess_region: data.guess_region,
                guess_points: data.guess_points,
            })
            .select()
            .single();

        if (insertError) {
            console.error('[saveTasting] Insert error:', {
                code: insertError.code,
                message: insertError.message,
                details: insertError.details,
                hint: insertError.hint,
                data: {
                    bottle_id: data.bottle_id,
                    user_id: user.id,
                    session_id: data.session_id
                }
            });

            // Check for RLS violation (42501)
            if ((insertError as any).code === '42501') {
                return {
                    success: false,
                    error: 'Keine Berechtigung zum Speichern (RLS). Prüfe ob du Besitzer der Flasche bist oder in einer aktiven Session teilnimmst.',
                    code: 'RLS_VIOLATION'
                };
            }
            throw insertError;
        }

        // Add buddy tags if any
        if (data.buddy_ids && data.buddy_ids.length > 0) {
            const buddies = data.buddy_ids.map(buddyId => ({
                tasting_id: tasting.id,
                buddy_id: buddyId,
                user_id: user.id
            }));
            const { error: tagError } = await supabase
                .from('tasting_buddies')
                .insert(buddies);

            if (tagError) {
                console.error('Error adding tasting buddies:', tagError);
                // We don't throw here to not fail the whole tasting save, 
                // but in a real app we might want more robust error handling
            }
        }

        // Add aroma tags if any
        if (data.tag_ids && data.tag_ids.length > 0) {
            const aromaTags = data.tag_ids.map(tagId => ({
                tasting_id: tasting.id,
                tag_id: tagId,
                user_id: user.id
            }));
            const { error: aromaTagError } = await supabase
                .from('tasting_tags')
                .insert(aromaTags);

            if (aromaTagError) {
                console.error('Error adding aroma tags:', aromaTagError);
            }
        }

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

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