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

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

  const createCustomer = useMutation({
    mutationFn: async (newCustomer: CustomerRequest) => {
      const response = await api.post('/customers', newCustomer)
      return response.data
    },
    onSuccess: () => {
      toast.success('Customer created successfully!')
      queryClient.invalidateQueries({ queryKey: ['customers'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

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

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

  return { createCustomer, updateCustomer, deleteCustomer }
}
