/** * Import types from Nadal. */ import { ref, computed } from 'vue' // import { useNadal } from '#lib/composables' import { useFavoriteGamesStore } from '#lib/stores/favorite-games' import { FavoriteGamesAction } from '#lib/enums/app' import { useUser, useAuth, useAPI } from '#lib/composables' import { useApiFetch } from '#lib/composables/service/use-api-fetch' import { AUTH_API } from '#lib/configs' import type { FavoritePayloadRequest, FavoriteResponse, } from '#lib/types/account' /** * Custom hook for Favorite Games by user. * @returns An object containing the favorite Games, loading status, onToggleFavoriteGames, favoriteGameNames * @namespace */ export const useFavoriteGames = () => { // const { account } = useNadal() const { isLogged } = useUser() const { openAuthModal } = useAuth() const { request } = useApiFetch() const storeFavorite = useFavoriteGamesStore() const isLoading = ref(false) const isLoadingToggle = ref(false) const favoriteGameNames = computed((): FavoriteResponse[] => { return storeFavorite.getFavoriteGames() }) /** * Fetches the favorite games from the server. * * FavoriteResponse[] type is imported from the Nadal module. * @returns An names array of favorite games by user. */ const fetchFavoriteGamesByUser = async (): Promise< FavoriteResponse[] | undefined > => { if (!isLogged.value) { return } isLoading.value = true try { const { data } = await request( AUTH_API.FAVORITE_GAME, ) storeFavorite.setFavoriteGames(data ?? []) return data } catch (ex) { console.error(' ~ useFavoriteGames ~ ex:', ex) } finally { isLoading.value = false } } /** * add, delete favorite Games from the server. * * FavoriteResponse[] type is imported from the Nadal module. * @returns An names array of favorite games by user. */ const onToggleFavoriteGames = async ( payload: FavoritePayloadRequest, action: FavoriteGamesAction, ): Promise => { if (!isLogged.value) { openAuthModal() return } isLoadingToggle.value = true const { error } = await useAPI(AUTH_API.FAVORITE_GAME, { method: action === FavoriteGamesAction.DELETE ? 'DELETE' : 'POST', body: payload, }) if (error.value) { throw error.value } fetchFavoriteGamesByUser() isLoadingToggle.value = false } return { fetchFavoriteGamesByUser, onToggleFavoriteGames, favoriteGameNames, isLoadingToggle, isLoading, } }