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

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

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

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

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

  return { createProduct, updateProduct, deleteProduct }
}
