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

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

  const createUnitConventer = useMutation({
    mutationFn: async (newUnitConventer: IngredientUnitConverterRequest) => {
      const response = await api.post('/unit-converters', newUnitConventer)
      return response.data
    },
    onSuccess: () => {
      toast.success('UnitConventer created successfully!')
      queryClient.invalidateQueries({ queryKey: ['unitConventers'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

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

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

  return { createUnitConventer, updateUnitConventer, deleteUnitConventer }
}
