/** Service for favorite-related API calls */
import { supabase } from '@/supabase'
import type { Favorite } from '@/types'

export const favoritesService = {
    /** Get all favorites for the current user */
    async getMyFavorites(itemType?: string): Promise<Favorite[]> {
        const { data: userData } = await supabase.auth.getUser()
        if (!userData?.user) return []

        let query = supabase.from('favorites').select('*').eq('user_id', userData.user.id)
        if (itemType) query = query.eq('item_type', itemType)
        const { data, error } = await query
        if (error) throw new Error(error.message)
        return data as Favorite[]
    },

    /** Add a new favorite */
    async addFavorite(
        itemType: 'route' | 'stop' | 'taxi' | 'coupon' | 'business',
        itemId: string,
        itemName?: string,
        itemImage?: string
    ): Promise<Favorite> {
        const { data: userData } = await supabase.auth.getUser()
        if (!userData?.user) throw new Error('Not authenticated')

        const { data, error } = await supabase.from('favorites').insert([{
            user_id: userData.user.id,
            item_type: itemType,
            item_id: itemId,
            item_name: itemName,
            item_image: itemImage
        }]).select().single()
        if (error) throw new Error(error.message)
        return data as Favorite
    },

    /** Remove a favorite by type and ID */
    async removeFavorite(itemType: string, itemId: string): Promise<void> {
        const { data: userData } = await supabase.auth.getUser()
        if (!userData?.user) throw new Error('Not authenticated')

        const { error } = await supabase.from('favorites')
            .delete()
            .eq('user_id', userData.user.id)
            .eq('item_type', itemType)
            .eq('item_id', itemId)
        if (error) throw new Error(error.message)
    },

    /** Remove a favorite by favorite ID */
    async removeFavoriteById(favoriteId: string): Promise<void> {
        const { error } = await supabase.from('favorites').delete().eq('id', favoriteId)
        if (error) throw new Error(error.message)
    },

    /** Check if an item is favorited */
    async checkFavorite(itemType: string, itemId: string): Promise<boolean> {
        try {
            const { data: userData } = await supabase.auth.getUser()
            if (!userData?.user) return false

            const { data } = await supabase.from('favorites')
                .select('id')
                .eq('user_id', userData.user.id)
                .eq('item_type', itemType)
                .eq('item_id', itemId)
                .single()
            return !!data
        } catch {
            return false
        }
    },

    /** Toggle favorite status */
    async toggleFavorite(
        itemType: 'route' | 'stop' | 'taxi' | 'coupon' | 'business',
        itemId: string,
        itemName?: string,
        itemImage?: string
    ): Promise<boolean> {
        const isFavorite = await this.checkFavorite(itemType, itemId)
        if (isFavorite) {
            await this.removeFavorite(itemType, itemId)
            return false
        } else {
            await this.addFavorite(itemType, itemId, itemName, itemImage)
            return true
        }
    }
}
