'use server';

import { createClient } from '@/lib/supabase/server';
import { BottleMetadataSchema } from '@/types/whisky';
import { v4 as uuidv4 } from 'uuid';

export async function saveBottle(
    rawMetadata: any,
    base64Image: string | null,
    _ignoredUserId: string, // Keeping for signature compatibility
    preUploadedUrl?: string
) {
    const supabase = await createClient();

    try {
        const metadata = BottleMetadataSchema.parse(rawMetadata);
        const { data: { session } } = await supabase.auth.getSession();
        if (!session) {
            throw new Error('Nicht autorisiert oder Session abgelaufen.');
        }

        const userId = session.user.id;
        let finalImageUrl = preUploadedUrl;

        // 1. Upload Image to Storage if not already uploaded
        if (!finalImageUrl && base64Image) {
            const base64Data = base64Image.split(',')[1] || base64Image;
            const buffer = Buffer.from(base64Data, 'base64');
            const fileName = `${userId}/${uuidv4()}.jpg`;

            const { error: uploadError } = await supabase.storage
                .from('bottles')
                .upload(fileName, buffer, {
                    contentType: 'image/jpeg',
                    upsert: true,
                });

            if (uploadError) throw new Error(`Upload Error: ${uploadError.message}`);

            // Get Public URL
            const { data: { publicUrl } } = supabase.storage
                .from('bottles')
                .getPublicUrl(fileName);

            finalImageUrl = publicUrl;
        }

        if (!finalImageUrl) {
            throw new Error('Kein Bild zum Speichern vorhanden.');
        }

        // 2. Save Metadata to Database
        const { data: bottleData, error: dbError } = await supabase
            .from('bottles')
            .insert({
                user_id: userId,
                name: metadata.name,
                distillery: metadata.distillery,
                category: metadata.category,
                abv: metadata.abv,
                age: metadata.age,
                whiskybase_id: metadata.whiskybaseId,
                image_url: finalImageUrl,
                status: 'sealed',
                is_whisky: metadata.is_whisky ?? true,
                confidence: metadata.confidence ?? 100,
                distilled_at: metadata.distilled_at,
                bottled_at: metadata.bottled_at,
                batch_info: metadata.batch_info,
                suggested_tags: metadata.suggested_tags,
                suggested_custom_tags: metadata.suggested_custom_tags,
            })
            .select()
            .single();

        if (dbError) throw new Error(`Database Error: ${dbError.message}`);

        return { success: true, data: bottleData };
    } catch (error) {
        console.error('Save Bottle Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'An unknown error occurred while saving.',
        };
    }
}
