import { useMutation, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { toast } from 'react-toastify'
import { InventoryAdjustRequest, InventoryRequest, InventoryRestockRequest } from '../../types/services/inventory'

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

  const createInventory = useMutation({
    mutationFn: async (newInventory: InventoryRequest) => {
      const response = await api.post('/inventory', newInventory)
      return response.data
    },
    onSuccess: () => {
      toast.success('Inventory created successfully!')
      queryClient.invalidateQueries({ queryKey: ['inventories'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

  const adjustInventory = useMutation({
    mutationFn: async (newInventory: InventoryAdjustRequest) => {
      const response = await api.post('/inventory/adjust', newInventory)
      return response.data
    },
    onSuccess: () => {
      toast.success('Inventory adjusted successfully!')
      queryClient.invalidateQueries({ queryKey: ['inventories'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

  const restockInventory = useMutation({
    mutationFn: async (newInventory: InventoryRestockRequest) => {
      newInventory.items.map(item => {
        item.quantity = Number(item.quantity)
      })

      const response = await api.post('/inventory/restock', newInventory)
      return response.data
    },
    onSuccess: () => {
      toast.success('Inventory restock successfully!')
      queryClient.invalidateQueries({ queryKey: ['inventories'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

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

  return { createInventory, adjustInventory, deleteInventory, restockInventory }
}
