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

export const favoritesService = {
    /** Get all favorites for the current user */
    async getMyFavorites(itemType?: string): Promise<Favorite[]> {
        const params = itemType ? { item_type: itemType } : {}
        const response = await apiClient.get<Favorite[]>('/api/favorites', { params })
        return response.data
    },

    /** Add a new favorite */
    async addFavorite(
        itemType: 'route' | 'stop' | 'taxi' | 'coupon' | 'business',
        itemId: string,
        itemName?: string,
        itemImage?: string
    ): Promise<Favorite> {
        const response = await apiClient.post<Favorite>('/api/favorites', {
            item_type: itemType,
            item_id: itemId,
            item_name: itemName,
            item_image: itemImage
        })
        return response.data
    },

    /** Remove a favorite by type and ID */
    async removeFavorite(itemType: string, itemId: string): Promise<void> {
        await apiClient.delete(`/api/favorites/${itemType}/${itemId}`)
    },

    /** Remove a favorite by favorite ID (legacy support) */
    async removeFavoriteById(favoriteId: string): Promise<void> {
        // This requires finding the favorite first to get type and id
        const favorites = await this.getMyFavorites()
        const favorite = favorites.find(f => f.id === favoriteId)
        if (favorite) {
            await this.removeFavorite(favorite.item_type, favorite.item_id)
        }
    },

    /** Check if an item is favorited */
    async checkFavorite(itemType: string, itemId: string): Promise<boolean> {
        try {
            const response = await apiClient.get<{ is_favorite: boolean }>(
                `/api/favorites/check/${itemType}/${itemId}`
            )
            return response.data.is_favorite
        } catch (error) {
            console.error('Error checking favorite:', error)
            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
        }
    }
}
