import {Assignment} from "@/interfaces/results";
import axios from "axios";
import {useEffect, useState} from "react";

export default function useAssignments({assigner, assignees}: {assigner?: string; assignees?: string}) {
	const [assignments, setAssignments] = useState<Assignment[]>([]);
	const [isLoading, setIsLoading] = useState(false);
	const [isError, setIsError] = useState(false);

	const getData = () => {
		setIsLoading(true);
		axios
			.get<Assignment[]>("/api/assignments")
			.then((response) => {
				if (assigner) {
					setAssignments(response.data.filter((a) => a.assigner === assigner));
					return;
				}
				if (assignees) {
					setAssignments(response.data.filter((a) => a.assignees.filter((x) => assignees.includes(x)).length > 0));
					return;
				}

				setAssignments(response.data);
			})
			.finally(() => setIsLoading(false));
	};

	useEffect(getData, [assignees, assigner]);

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