import { GameRequest } from '@/types/services/game'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-toastify'
import { api } from '../api'

export const useGamesMutation = () => {
  const queryClient = useQueryClient()

  const createGame = useMutation({
    mutationFn: async (newGame: GameRequest) => {
      const response = await api.post('/marketing/games', newGame)
      return response.data
    },
    onSuccess: () => {
      toast.success('Game created successfully!')
      queryClient.invalidateQueries({ queryKey: ['games'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

  const updateGame = useMutation({
    mutationFn: async ({ id, payload }: { id: string; payload: GameRequest }) => {
      const response = await api.put(`/marketing/games/${id}`, payload)
      return response.data
    },
    onSuccess: () => {
      toast.success('Game updated successfully!')
      queryClient.invalidateQueries({ queryKey: ['games'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
    }
  })

  const deleteGame = useMutation({
    mutationFn: async (id: string) => {
      const response = await api.delete(`/marketing/games/${id}`)
      return response.data
    },
    onSuccess: () => {
      toast.success('Game deleted successfully!')
      queryClient.invalidateQueries({ queryKey: ['games'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
    }
  })

  return { createGame, updateGame, deleteGame }
}
