'use server';

import { createServerActionClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { BottleMetadata } from '@/types/whisky';
import { v4 as uuidv4 } from 'uuid';

export async function saveBottle(
    metadata: BottleMetadata,
    base64Image: string,
    _ignoredUserId: string // Keeping for signature compatibility if needed, but using session internally
) {
    const supabase = createServerActionClient({ cookies });

    try {
        // Verify user session and get ID from the server side (secure)
        const { data: { session } } = await supabase.auth.getSession();
        if (!session) {
            throw new Error('Nicht autorisiert oder Session abgelaufen.');
        }

        const userId = session.user.id;

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

        const { data: uploadData, 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);

        // 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: publicUrl,
                status: 'sealed', // Default status
            })
            .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.',
        };
    }
}
