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

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

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

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

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

  return { createReward, updateReward, deleteReward }
}
