import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { Game, Games } from '@/types/services/game'

interface GameQueryParams {
  page?: number
  limit?: number
  search?: string
}

export function useGames(params: GameQueryParams = {}) {
  const { page = 1, limit = 10, search = '', ...filters } = params

  return useQuery<Games>({
    queryKey: ['games', { page, limit, search, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('page', page.toString())
      queryParams.append('limit', limit.toString())

      if (search) {
        queryParams.append('search', search)
      }

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/marketing/games?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useGameById(id: string) {
  return useQuery<Game>({
    queryKey: ['games', id],
    queryFn: async () => {
      const res = await api.get(`/marketing/games/${id}`)
      return res.data.data
    }
  })
}
