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

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

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

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

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

  return { createIngredient, updateIngredient, deleteIngredient }
}
