import {Type, User} from "@/interfaces/user";
import Axios from "axios";
import {useEffect, useState} from "react";
import {setupCache} from "axios-cache-interceptor";

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

export default function useUsers(props?: {type?: Type; page?: number; size?: number}) {
	const [users, setUsers] = useState<User[]>([]);
	const [isLoading, setIsLoading] = useState(false);
	const [isError, setIsError] = useState(false);

	const getData = () => {
		const params = new URLSearchParams();
		if (!!props)
			Object.keys(props).forEach((key) => {
				if (!!props[key as keyof typeof props]) params.append(key, props[key as keyof typeof props]!.toString());
			});

		setIsLoading(true);
		axios
			.get<User[]>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
			.then((response) => setUsers(response.data))
			.finally(() => setIsLoading(false));
	};

	useEffect(getData, [props]);

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