'use server';

/**
 * Service to save OCR results to the database
 */

import { createClient } from '@/lib/supabase/server';

export interface OcrLogEntry {
    imageUrl?: string;
    imageThumbnail?: string;
    rawText: string;
    detectedTexts: string[];
    distillery?: string | null;
    distillerySource?: 'fuzzy' | 'ai' | 'manual' | null;
    bottleName?: string | null;
    abv?: number | null;
    age?: number | null;
    vintage?: string | null;
    volume?: string | null;
    category?: string | null;
    confidence: number;
    deviceInfo?: string;
    ocrMethod: string;
    processingTimeMs?: number;
    bottleId?: string;
}

export async function saveOcrLog(entry: OcrLogEntry): Promise<{ success: boolean; id?: string; error?: string }> {
    try {
        const supabase = await createClient();
        const { data: { user } } = await supabase.auth.getUser();

        if (!user) {
            console.warn('[saveOcrLog] No authenticated user');
            return { success: false, error: 'Not authenticated' };
        }

        const { data, error } = await supabase
            .from('ocr_logs')
            .insert({
                user_id: user.id,
                bottle_id: entry.bottleId || null,
                image_url: entry.imageUrl || null,
                image_thumbnail: entry.imageThumbnail || null,
                raw_text: entry.rawText,
                detected_texts: entry.detectedTexts,
                distillery: entry.distillery || null,
                distillery_source: entry.distillerySource || null,
                bottle_name: entry.bottleName || null,
                abv: entry.abv || null,
                age: entry.age || null,
                vintage: entry.vintage || null,
                volume: entry.volume || null,
                category: entry.category || null,
                confidence: entry.confidence,
                device_info: entry.deviceInfo || null,
                ocr_method: entry.ocrMethod,
                processing_time_ms: entry.processingTimeMs || null,
            })
            .select('id')
            .single();

        if (error) {
            console.error('[saveOcrLog] Insert error:', error);
            return { success: false, error: error.message };
        }

        console.log('[saveOcrLog] Saved OCR log:', data?.id);
        return { success: true, id: data?.id };
    } catch (err: any) {
        console.error('[saveOcrLog] Error:', err);
        return { success: false, error: err.message };
    }
}

/**
 * Get OCR logs for admin dashboard
 */
export async function getOcrLogs(limit: number = 50): Promise<{
    success: boolean;
    data?: any[];
    error?: string;
}> {
    try {
        const supabase = await createClient();

        const { data, error } = await supabase
            .from('ocr_logs')
            .select(`
                *,
                profiles:user_id (username)
            `)
            .order('created_at', { ascending: false })
            .limit(limit);

        if (error) {
            console.error('[getOcrLogs] Query error:', error);
            return { success: false, error: error.message };
        }

        return { success: true, data: data || [] };
    } catch (err: any) {
        console.error('[getOcrLogs] Error:', err);
        return { success: false, error: err.message };
    }
}

/**
 * Get OCR stats for admin dashboard
 */
export async function getOcrStats(): Promise<{
    totalScans: number;
    todayScans: number;
    avgConfidence: number;
    topDistilleries: { name: string; count: number }[];
}> {
    try {
        const supabase = await createClient();
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        // Total scans
        const { count: totalScans } = await supabase
            .from('ocr_logs')
            .select('*', { count: 'exact', head: true });

        // Today's scans
        const { count: todayScans } = await supabase
            .from('ocr_logs')
            .select('*', { count: 'exact', head: true })
            .gte('created_at', today.toISOString());

        // Average confidence
        const { data: confidenceData } = await supabase
            .from('ocr_logs')
            .select('confidence');

        const avgConfidence = confidenceData && confidenceData.length > 0
            ? Math.round(confidenceData.reduce((sum, d) => sum + (d.confidence || 0), 0) / confidenceData.length)
            : 0;

        // Top distilleries
        const { data: distilleryData } = await supabase
            .from('ocr_logs')
            .select('distillery')
            .not('distillery', 'is', null);

        const distilleryCounts = new Map<string, number>();
        distilleryData?.forEach(d => {
            if (d.distillery) {
                distilleryCounts.set(d.distillery, (distilleryCounts.get(d.distillery) || 0) + 1);
            }
        });

        const topDistilleries = Array.from(distilleryCounts.entries())
            .map(([name, count]) => ({ name, count }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 5);

        return {
            totalScans: totalScans || 0,
            todayScans: todayScans || 0,
            avgConfidence,
            topDistilleries,
        };
    } catch (err) {
        console.error('[getOcrStats] Error:', err);
        return {
            totalScans: 0,
            todayScans: 0,
            avgConfidence: 0,
            topDistilleries: [],
        };
    }
}
