/**
 * WordPress dependencies
 */
import apiFetch from "@wordpress/api-fetch";
import { addQueryArgs } from "@wordpress/url";

const WP_BASE_PATH = "/wp/v2/";
export const useWPService = () => {
	/**
	 * Function to get list of WP users
	 *
	 * @param {Object} response component property
	 * response: {
	 * 			data: Array, - list of users
	 * 			totalPages: number - total of users from the search
	 * 		}
	 *
	 */

	const fetchUsers = async ({
		searchText = "",
		currentPage = 1,
		includeUsers = [],
		perPage = 10,
	}) => {
		const queryParams = {
			search: searchText,
			page: currentPage,
			per_page: perPage,
			include: includeUsers,
		};

		try {
			return apiFetch({
				path: addQueryArgs(`${WP_BASE_PATH}users`, queryParams),
				parse: false,
			})
				.then((response) => {
					const { ok, headers } = response;
					if (ok) {
						return Promise.all([
							response.json(),
							parseInt(headers.get("x-wp-totalpages")),
						]);
					}
					return Promise.reject();
				})
				.then(([data, totalPages]) => {
					return {
						data,
						totalPages,
					};
				})
				.catch(() => {
					return null;
				});
		} catch (error) {
			return null;
		}
	};

	return { fetchUsers };
};
