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

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

  const createPaymentMethod = useMutation({
    mutationFn: async (newPaymentMethod: PaymentMethodRequest) => {
      const response = await api.post('/payment-methods', newPaymentMethod)
      return response.data
    },
    onSuccess: () => {
      toast.success('PaymentMethod created successfully!')
      queryClient.invalidateQueries({ queryKey: ['payment-methods'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

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

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

  return { createPaymentMethod, updatePaymentMethod, deletePaymentMethod }
}
