import apiFetch from "@wordpress/api-fetch";

function cfg() {
	return (window && window.JetMenuNavSettings) ? window.JetMenuNavSettings : {};
}

export function setupApiFetch() {
	const { restUrl, nonce } = cfg();

	if (restUrl) {
		apiFetch.use(apiFetch.createRootURLMiddleware(restUrl));
	}
	if (nonce) {
		apiFetch.use(apiFetch.createNonceMiddleware(nonce));
	}
}

export async function getMenus() {
	return apiFetch({path: "/wp/v2/menus?per_page=100"});
}

export async function createMenu({name, description = ""}) {
	return apiFetch({path: "/wp/v2/menus", method: "POST", data: {name, description}});
}

export async function deleteMenu(menuId) {
	return apiFetch({ path: `/wp/v2/menus/${menuId}?force=true`, method: "DELETE" });
}

export async function getMenuItems(menuId) {
	return apiFetch({path: `/wp/v2/menu-items?menus=${menuId}&per_page=100`});
}

export async function createMenuItem(data) {
	return apiFetch({path: "/wp/v2/menu-items", method: "POST", data});
}

export async function updateMenuItem(id, data) {
	return apiFetch({path: `/wp/v2/menu-items/${id}`, method: "POST", data});
}

export async function deleteMenuItem(id) {
	return apiFetch({path: `/wp/v2/menu-items/${id}?force=true`, method: "DELETE"});
}

export async function getTypes() {
	return apiFetch({path: "/wp/v2/types"});
}

export async function getTaxonomies() {
	return apiFetch({path: "/wp/v2/taxonomies"});
}

export async function searchPosts(restBase, {search = "", perPage = 20} = {}) {
	const q = encodeURIComponent(search || "");
	return apiFetch({path: `/wp/v2/${restBase}?per_page=${perPage}&search=${q}`});
}

export async function searchTerms(restBase, {search = "", perPage = 20} = {}) {
	const q = encodeURIComponent(search || "");
	return apiFetch({path: `/wp/v2/${restBase}?per_page=${perPage}&search=${q}`});
}
