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

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

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

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

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

  return { createVendor, updateVendor, deleteVendor }
}
