/** Hooks for the Authentik directory + messaging tabs. */
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
	fetchAuthentikMessageStatus,
	fetchAuthentikUsers,
	sendAuthentikMessage,
} from "../api/authentik";

export function useAuthentikUsers(
	serviceId: string,
	params: { search?: string; page?: number; page_size?: number },
) {
	return useQuery({
		queryKey: ["authentik", "users", serviceId, params],
		queryFn: () => fetchAuthentikUsers(serviceId, params),
		staleTime: 10_000,
	});
}

export function useSendAuthentikMessage(serviceId: string) {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (input: {
			recipient_emails: string[];
			subject: string;
			html_body: string;
		}) => sendAuthentikMessage(serviceId, input),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: ["authentik", "message-status", serviceId],
			});
		},
	});
}

export function useAuthentikMessageStatus(serviceId: string) {
	return useQuery({
		queryKey: ["authentik", "message-status", serviceId],
		queryFn: () => fetchAuthentikMessageStatus(serviceId),
		refetchInterval: 5_000,
		staleTime: 0,
	});
}
