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

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

  const createProductRecipe = useMutation({
    mutationFn: async (newProductRecipe: ProductRecipeRequest) => {
      const { variant_id, ...rest } = newProductRecipe

      const cleanRequest = variant_id ? newProductRecipe : rest

      const response = await api.post('/product-recipes', cleanRequest)
      return response.data
    },
    onSuccess: () => {
      toast.success('Product Recipe created successfully!')
      queryClient.invalidateQueries({ queryKey: ['product-recipes'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

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

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

  return {
    createProductRecipe,
    updateProductRecipe,
    deleteProductRecipe
  }
}
