'use server';

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

export async function findMatchingBottle(metadata: BottleMetadata) {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return null;

        const userId = user.id;

        // 1. Try matching by Whiskybase ID (most reliable)
        if (metadata.whiskybaseId) {
            const { data: wbMatch } = await supabase
                .from('bottles')
                .select('id, name, distillery')
                .eq('user_id', userId)
                .eq('whiskybase_id', metadata.whiskybaseId)
                .maybeSingle();

            if (wbMatch) return wbMatch;
        }

        // 2. Try matching by Name and Distillery (approximate)
        if (metadata.name && metadata.distillery) {
            const { data: nameMatch } = await supabase
                .from('bottles')
                .select('id, name, distillery')
                .eq('user_id', userId)
                .ilike('name', metadata.name)
                .ilike('distillery', metadata.distillery)
                .maybeSingle();

            if (nameMatch) return nameMatch;
        }

        return null;
    } catch (error) {
        console.error('Find Matching Bottle Error:', error);
        return null;
    }
}
