'use server';

import { createClient } from '@/lib/supabase/server';
import { revalidatePath } from 'next/cache';
import { analyzeBottleLabel } from '@/app/actions/scanner';

export interface BulkScanResult {
    success: boolean;
    bottleIds?: string[];
    tastingIds?: string[];
    error?: string;
}

/**
 * Process multiple bottle images in bulk for a tasting session.
 * Creates skeleton bottles immediately and triggers background AI analysis.
 * 
 * @param sessionId - The tasting session to link bottles to
 * @param imageDataUrls - Array of base64 image data URLs
 */
export async function processBulkScan(
    sessionId: string,
    imageDataUrls: string[]
): Promise<BulkScanResult> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        // Verify session exists and belongs to user
        const { data: session, error: sessionError } = await supabase
            .from('tasting_sessions')
            .select('id')
            .eq('id', sessionId)
            .eq('user_id', user.id)
            .single();

        if (sessionError || !session) {
            return { success: false, error: 'Session nicht gefunden' };
        }

        const bottleIds: string[] = [];
        const tastingIds: string[] = [];

        // Process each image
        for (let i = 0; i < imageDataUrls.length; i++) {
            const imageDataUrl = imageDataUrls[i];

            // 1. Upload image to Supabase Storage
            const imageUrl = await uploadImage(supabase, user.id, imageDataUrl);

            // 2. Create skeleton bottle with pending status
            const { data: bottle, error: bottleError } = await supabase
                .from('bottles')
                .insert({
                    user_id: user.id,
                    name: `Wird analysiert... (#${i + 1})`,
                    processing_status: 'pending',
                    image_url: imageUrl,
                    status: 'sealed',
                })
                .select('id')
                .single();

            if (bottleError || !bottle) {
                console.error('Error creating bottle:', bottleError);
                continue;
            }

            bottleIds.push(bottle.id);

            // 3. Create tasting to link bottle to session
            const { data: tasting, error: tastingError } = await supabase
                .from('tastings')
                .insert({
                    bottle_id: bottle.id,
                    user_id: user.id,
                    session_id: sessionId,
                    // No rating yet - placeholder tasting
                })
                .select('id')
                .single();

            if (tastingError) {
                console.error('Error creating tasting:', tastingError);
            } else if (tasting) {
                tastingIds.push(tasting.id);
            }
        }

        // 4. Trigger background analysis for all bottles (fire & forget)
        // Pass BOTH the bottle IDs and the original base64 images
        triggerBackgroundAnalysis(bottleIds, imageDataUrls, user.id).catch(err => {
            console.error('Background analysis error:', err);
        });

        revalidatePath(`/sessions/${sessionId}`);
        revalidatePath('/');

        return {
            success: true,
            bottleIds,
            tastingIds,
        };
    } catch (error) {
        console.error('processBulkScan error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Unbekannter Fehler',
        };
    }
}

/**
 * Upload a base64 image to Supabase Storage
 */
async function uploadImage(
    supabase: Awaited<ReturnType<typeof createClient>>,
    userId: string,
    dataUrl: string
): Promise<string | null> {
    try {
        // Convert base64 to blob
        const base64Data = dataUrl.split(',')[1];
        const mimeType = dataUrl.match(/data:(.*?);/)?.[1] || 'image/webp';
        const byteCharacters = atob(base64Data);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: mimeType });

        // Generate unique filename
        const ext = mimeType.split('/')[1] || 'webp';
        const filename = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;

        // Upload to storage
        const { error: uploadError } = await supabase.storage
            .from('bottles')
            .upload(filename, blob, {
                contentType: mimeType,
                upsert: false,
            });

        if (uploadError) {
            console.error('Upload error:', uploadError);
            return null;
        }

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

        return publicUrl;
    } catch (error) {
        console.error('Image upload failed:', error);
        return null;
    }
}

/**
 * Trigger background AI analysis for bottles.
 * This runs asynchronously and updates bottles with results.
 */
async function triggerBackgroundAnalysis(
    bottleIds: string[],
    imageDataUrls: string[],
    userId: string
): Promise<void> {
    const supabase = await createClient();

    for (let i = 0; i < bottleIds.length; i++) {
        const bottleId = bottleIds[i];
        const imageDataUrl = imageDataUrls[i];

        try {
            // Update status to analyzing
            await supabase
                .from('bottles')
                .update({ processing_status: 'analyzing' })
                .eq('id', bottleId);

            // Call AI analysis with the base64 data directly
            const analysisResult = await analyzeBottleLabel(imageDataUrl);

            if (analysisResult.success && analysisResult.data) {
                // Update bottle with AI results
                await supabase
                    .from('bottles')
                    .update({
                        name: analysisResult.data.name || 'Unbekannter Whisky',
                        distillery: analysisResult.data.distillery,
                        category: analysisResult.data.category,
                        abv: analysisResult.data.abv,
                        age: analysisResult.data.age,
                        is_whisky: analysisResult.data.is_whisky ?? true,
                        confidence: analysisResult.data.confidence ?? 80,
                        processing_status: 'complete',
                        updated_at: new Date().toISOString(),
                    })
                    .eq('id', bottleId);
            } else {
                await markBottleError(supabase, bottleId, analysisResult.error || 'Analyse fehlgeschlagen');
            }
        } catch (error) {
            console.error(`Analysis failed for bottle ${bottleId}:`, error);
            await markBottleError(supabase, bottleId, 'Analysefehler');
        }
    }
}

async function markBottleError(
    supabase: Awaited<ReturnType<typeof createClient>>,
    bottleId: string,
    error: string
): Promise<void> {
    await supabase
        .from('bottles')
        .update({
            processing_status: 'error',
            name: `Fehler: ${error.slice(0, 50)}`,
            updated_at: new Date().toISOString(),
        })
        .eq('id', bottleId);
}



/**
 * Get bottles for a session with their processing status
 */
export async function getSessionBottles(sessionId: string): Promise<{
    success: boolean;
    bottles?: Array<{
        id: string;
        name: string;
        distillery?: string;
        abv?: number;
        age?: number;
        image_url?: string;
        processing_status: string;
        tasting_id: string;
    }>;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { data, error } = await supabase
            .from('tastings')
            .select(`
                id,
                bottles (
                    id,
                    name,
                    distillery,
                    abv,
                    age,
                    image_url,
                    processing_status
                )
            `)
            .eq('session_id', sessionId)
            .eq('user_id', user.id);

        if (error) {
            return { success: false, error: error.message };
        }

        const bottles = (data || [])
            .filter(t => t.bottles)
            .map(t => ({
                ...(t.bottles as any),
                tasting_id: t.id,
            }));

        return { success: true, bottles };
    } catch (error) {
        return { success: false, error: 'Fehler beim Laden' };
    }
}
