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

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

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

  const updateUser = useMutation({
    mutationFn: async ({ id, payload }: { id: string; payload: UserRequest }) => {
      const {password, ...rest} = payload

      const response = await api.put(`/users/${id}`, rest)
      return response.data
    },
    onSuccess: () => {
      toast.success('User updated successfully!')
      queryClient.invalidateQueries({ queryKey: ['users'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
    }
  })

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

  return { createUser, updateUser, deleteUser }
}
