import * as api from "../service/RolesService";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { CreateRoleType } from "../types/Types";

export const useGetRoles = (params?: api.GetRolesParams) => {
  return useQuery({
    queryKey: ["roles", params],
    queryFn: () => api.getRoles(params),
  });
};

export const useGetRoleDetails = (id: string) => {
  return useQuery({
    queryKey: ["roles", id],
    queryFn: () => api.getRoleDetails(id),
    enabled: !!id,
  });
};

export const useDeleteRole = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteRole,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["roles"] });
    },
  });
};

export const useCreateRole = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createRole,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["roles"] });
    },
  });
};

export const useUpdateRole = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateRoleType }) =>
      api.updateRole(id, params),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ["roles"] });
      queryClient.invalidateQueries({ queryKey: ["roles", id] });
    },
  });
};
