import { useMutation, useQueryClient } from '@tanstack/react-query'
import { updateUserPermisosOverrides } from '../api/updateUserPermisosOverrides'
import type { UpdatePermisosOverridesPayload, UsuarioPermisos } from '../types'
import { userPermisosQueryKey } from './useUserPermisos'
import { userQueryKey } from './useUser'

export function useUpdateUserPermisosOverrides(userId: number) {
  const queryClient = useQueryClient()

  return useMutation<UsuarioPermisos, Error, UpdatePermisosOverridesPayload>({
    mutationFn: (payload) => updateUserPermisosOverrides(userId, payload),
    onSuccess: () => {
      // Invalidate the specific user's permisos query
      queryClient.invalidateQueries({ queryKey: userPermisosQueryKey(userId) })
      // Invalidate the user detail query (in case effective permisos affect UI elsewhere)
      queryClient.invalidateQueries({ queryKey: userQueryKey(userId) })
      // Invalidate the users list
      queryClient.invalidateQueries({ queryKey: ['users'] })
    },
  })
}
