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

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

	const getData = () => {
		setIsLoading(true);
		axios
			.get<Assignment[]>(!corporate ? "/api/assignments" : `/api/assignments/corporate/${corporate}`)
			.then(async (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, corporate]);

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