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

interface Setting {
	key: string;
	value: string;
}

export function useSetting(key: string) {
	return useQuery({
		queryKey: ["settings", key],
		queryFn: async () => {
			try {
				const result = await apiGet<Setting>(`/api/settings/${key}`);
				return result.value;
			} catch (err: any) {
				if (err?.status === 404) return null;
				throw err;
			}
		},
	});
}

export function useUpdateSetting() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({ key, value }: { key: string; value: string }) =>
			apiPut<Setting>(`/api/settings/${key}`, { value }),
		onSuccess: (_data, variables) => {
			queryClient.invalidateQueries({ queryKey: ["settings", variables.key] });
		},
	});
}

export function useOnboardingComplete(enabled = true) {
	return useQuery({
		queryKey: ["settings", "onboardingComplete"],
		queryFn: async () => {
			try {
				const result = await apiGet<Setting>(
					`/api/settings/onboardingComplete`,
				);
				return result.value;
			} catch (err: any) {
				if (err?.status === 404) return null;
				throw err;
			}
		},
		enabled,
	});
}
