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

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

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

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

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

  return { createTier, updateTier, deleteTier }
}
