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

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

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

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

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

  return { createUnit, updateUnit, deleteUnit }
}
