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

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

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

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

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

  return { createCategory, updateCategory, deleteCategory }
}
