import { useEffect, useLayoutEffect, useRef } from "react"
import { devlog } from "@frontend/kitui"

import { ServiceKeyToPrivilegesMap } from "@root/model/privilege"
import { getCustomTariffs } from "@root/api/tariff"

export function useCustomTariffs({
	onError,
	onNewUser,
}: {
  onNewUser: (response: ServiceKeyToPrivilegesMap) => void;
  onError: (error: any) => void;
}) {
	const onNewUserRef = useRef(onNewUser)
	const onErrorRef = useRef(onError)

	useLayoutEffect(() => {
		onNewUserRef.current = onNewUser
		onErrorRef.current = onError
	})

	useEffect(() => {
		const controller = new AbortController()

		getCustomTariffs(controller.signal)
			.then(([customTariffs]) => {
				if (customTariffs) {
					onNewUserRef.current(customTariffs)
				}
			})
			.catch(([_, error]) => {
				devlog("Error fetching custom tariffs", error)
				onErrorRef.current(error)
			})

		return () => controller.abort()
	}, [])
}
