import {Exam} from "@/interfaces/exam";
import {Permission, PermissionType} from "@/interfaces/permissions";
import {ExamState} from "@/stores/examStore";
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
					.filter((x) => !x.users.includes(user))
					.reduce((acc, curr) => [...acc, curr.type], [] as PermissionType[]);
				setPermissions(permissionTypes);
			})
			.finally(() => setIsLoading(false));
	};

	useEffect(getData, [user]);

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