'use server';

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

interface EnrichmentCacheData {
    suggested_tags: string[] | null;
    suggested_custom_tags: string[] | null;
    search_string: string | null;
}

/**
 * Get cached enrichment data for a distillery
 */
export async function getEnrichmentCache(distillery: string): Promise<EnrichmentCacheData | null> {
    if (!distillery?.trim()) return null;

    const supabase = await createClient();
    const normalizedDistillery = distillery.trim().toLowerCase();

    const { data, error } = await supabase
        .from('enrichment_cache')
        .select('suggested_tags, suggested_custom_tags, search_string')
        .eq('distillery', normalizedDistillery)
        .single();

    if (error || !data) {
        return null;
    }

    return data;
}

/**
 * Save enrichment data to cache
 */
export async function saveEnrichmentCache(
    distillery: string,
    enrichmentData: EnrichmentCacheData
): Promise<boolean> {
    if (!distillery?.trim()) return false;

    const supabase = await createClient();
    const normalizedDistillery = distillery.trim().toLowerCase();

    const { error } = await supabase
        .from('enrichment_cache')
        .upsert({
            distillery: normalizedDistillery,
            suggested_tags: enrichmentData.suggested_tags,
            suggested_custom_tags: enrichmentData.suggested_custom_tags,
            search_string: enrichmentData.search_string,
            updated_at: new Date().toISOString(),
        }, {
            onConflict: 'distillery'
        });

    if (error) {
        console.error('[EnrichmentCache] Save error:', error);
        return false;
    }

    console.log(`[EnrichmentCache] Saved cache for: ${normalizedDistillery}`);
    return true;
}

/**
 * Increment cache hit counter
 */
export async function incrementCacheHit(distillery: string): Promise<void> {
    if (!distillery?.trim()) return;

    const supabase = await createClient();
    const normalizedDistillery = distillery.trim().toLowerCase();

    // Simple increment via update - no RPC needed
    const { data: current } = await supabase
        .from('enrichment_cache')
        .select('hit_count')
        .eq('distillery', normalizedDistillery)
        .single();

    if (current) {
        await supabase
            .from('enrichment_cache')
            .update({ hit_count: (current.hit_count || 0) + 1 })
            .eq('distillery', normalizedDistillery);
    }
}

/**
 * Get cache statistics
 */
export async function getEnrichmentCacheStats() {
    const supabase = await createClient();

    const { data, error } = await supabase
        .from('enrichment_cache')
        .select('distillery, hit_count, created_at')
        .order('hit_count', { ascending: false })
        .limit(20);

    if (error) {
        console.error('[EnrichmentCache] Stats error:', error);
        return [];
    }

    return data || [];
}
