'use server';

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

import { TagSchema, TagData } from '@/types/whisky';

export type TagCategory = 'nose' | 'taste' | 'finish' | 'texture';

export interface Tag {
    id: string;
    name: string;
    category: TagCategory;
    is_system_default: boolean;
    popularity_score: number;
    created_by?: string;
}

/**
 * Fetch tags by category
 */
export async function getTagsByCategory(category: TagCategory): Promise<Tag[]> {
    try {
        const supabase = await createClient();

        const { data, error } = await supabase
            .from('tags')
            .select('*')
            .eq('category', category)
            .order('popularity_score', { ascending: false })
            .order('name');

        if (error) {
            console.error(`Error fetching tags for ${category}:`, error);
            return [];
        }

        return data || [];
    } catch (err) {
        console.error(`Exception in getTagsByCategory for ${category}:`, err);
        return [];
    }
}

/**
 * Fetch all system default tags
 */
export async function getAllSystemTags(): Promise<Tag[]> {
    try {
        const supabase = await createClient();

        const { data, error } = await supabase
            .from('tags')
            .select('*')
            .eq('is_system_default', true)
            .order('name');

        if (error) {
            console.error('Error fetching all system tags:', error);
            return [];
        }

        return data || [];
    } catch (err) {
        console.error('Exception in getAllSystemTags:', err);
        return [];
    }
}

/**
 * Create a custom user tag
 */
export async function createCustomTag(rawName: string, rawCategory: TagCategory): Promise<{ success: boolean; tag?: Tag; error?: string }> {
    const supabase = await createClient();

    try {
        const { name, category } = TagSchema.parse({ name: rawName, category: rawCategory });
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) throw new Error('Nicht autorisiert');

        const { data, error } = await supabase
            .from('tags')
            .insert({
                name,
                category,
                is_system_default: false,
                created_by: user.id
            })
            .select()
            .single();

        if (error) {
            if (error.code === '23505') { // Unique constraint violation
                // Try to fetch the existing tag
                const { data: existingTag } = await supabase
                    .from('tags')
                    .select('*')
                    .eq('name', name)
                    .eq('category', category)
                    .single();

                return { success: true, tag: existingTag || undefined };
            }
            throw error;
        }

        return { success: true, tag: data };
    } catch (error) {
        console.error('Error creating custom tag:', error);
        return { success: false, error: 'Tag konnte nicht erstellt werden' };
    }
}
