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

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

  const createPurchaseOrder = useMutation({
    mutationFn: async (newPurchaseOrder: PurchaseOrderRequest) => {
      const response = await api.post('/purchase-orders', newPurchaseOrder)
      return response.data
    },
    onSuccess: () => {
      toast.success('Purchase Order created successfully!')
      queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

  const sendPaymentPurchaseOrder = useMutation({
    mutationFn: async ({ id, payload }: { id: string; payload: SendPaymentPurchaseOrderRequest }) => {
      const response = await api.put(`/purchase-orders/${id}`, payload)
      return response.data
    },
    onSuccess: () => {
      toast.success('Purchase Order created successfully!')
      queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

  return { createPurchaseOrder, sendPaymentPurchaseOrder }
}
