'use server';

/**
 * Service to search Brave for a Whiskybase link and extract the ID.
 */
export async function searchBraveForWhiskybase(query: string) {
    const apiKey = process.env.BRAVE_API_KEY;

    if (!apiKey) {
        console.error('BRAVE_API_KEY is not configured.');
        return { success: false, error: 'Brave Search API Key missing.' };
    }

    try {
        const url = `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query + ' site:whiskybase.com')}`;

        const response = await fetch(url, {
            headers: {
                'X-Subscription-Token': apiKey,
                'Accept': 'application/json',
            }
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || `Brave API error: ${response.status}`);
        }

        const data = await response.json();

        if (!data.web || !data.web.results || data.web.results.length === 0) {
            return { success: false, error: 'No results found on Brave.' };
        }

        // Try to find a Whiskybase ID in the results
        const wbRegex = /whiskybase\.com\/whiskies\/whisky\/(\d+)\//;

        for (const result of data.web.results) {
            const url = result.url;
            const match = url.match(wbRegex);

            if (match && match[1]) {
                return {
                    success: true,
                    id: match[1],
                    url: url,
                    title: result.title
                };
            }
        }

        return { success: false, error: 'No valid Whiskybase ID found in results.' };
    } catch (error) {
        console.error('Brave Search Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error during Brave search.'
        };
    }
}
