import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiDelete, apiGet, apiPost } from "../lib/api";

interface ShareLink {
	id: number;
	setupId: number;
	token: string;
	permission: string;
	expiresAt: string | null;
	createdAt: string;
	revokedAt: string | null;
}

export function useShareLinks(setupId: number | null) {
	return useQuery({
		queryKey: ["shares", setupId],
		queryFn: () => apiGet<ShareLink[]>(`/api/setups/${setupId}/shares`),
		enabled: !!setupId,
	});
}

export function useCreateShareLink(setupId: number) {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (data: { expiresInDays: number | null }) =>
			apiPost<ShareLink>(`/api/setups/${setupId}/shares`, data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["shares", setupId] });
		},
	});
}

export function useRevokeShareLink(setupId: number) {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (shareId: number) =>
			apiDelete<ShareLink>(`/api/setups/${setupId}/shares/${shareId}`),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["shares", setupId] });
		},
	});
}
