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

export const useGetAdmins = (params?: GetAdminsParams) => {
  return useQuery({
    queryKey: ["admins", params],
    queryFn: () => api.getAdmins(params),
  });
};

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

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

export const useUpdateAdmin = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateAdminType }) =>
      api.updateAdmin(id, params),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({
        queryKey: ["admins"],
      });
      queryClient.invalidateQueries({
        queryKey: ["admins", id],
      });
    },
  });
};

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