import {Permission, PermissionType} from "@/interfaces/permissions";
import Axios from "axios";
import {setupCache} from "axios-cache-interceptor";
import {useEffect, useState} from "react";

const instance = Axios.create();
const axios = setupCache(instance);

export default function usePermissions(user: string) {
	const [permissions, setPermissions] = useState<PermissionType[]>([]);
	const [isLoading, setIsLoading] = useState(false);
	const [isError, setIsError] = useState(false);

	const getData = () => {
		setIsLoading(true);
		axios
			.get<Permission[]>(`/api/permissions`)
			.then((response) => {
				const permissionTypes = response.data
					.reduce((acc, curr) => curr.users.includes(user)? acc : [...acc, curr.type], [] as PermissionType[]);
				setPermissions(permissionTypes);
			})
			.finally(() => setIsLoading(false));
	};

	useEffect(getData, [user]);

	return {permissions, isLoading, isError, reload: getData};
}
