import { addQueryParams } from "./_global--url-helper.js";
import { extractJson } from "./_global--extract-json.js";
import { jsVar, jsVarExists } from "./_global--enqueue-loader.js";




export async function fetchEndpoint(path, options = {}) {

    if (!path.startsWith("/wp-json/neo/")) { throw new Error("The endpoint path must start with '/wp-json/neo/'."); }
    let { url, isPublic } = jsVar("neoGlobalRestEndpoints")[path] ?? {};
    if (!url) { throw new Error(`The endpoint '${path}' is not registered or available.`); }
    options = { ...options };
    if (options.query) {
        url = addQueryParams(url, options.query);
        delete options.query;
    }
    if (options.suppressHttpCodeError) { delete options.suppressHttpCodeError; }
    if (options.body && !(options.body instanceof FormData)) { options.headers ??= {}; options.headers["Content-Type"] = "application/json"; if (typeof options.body === "object") { options.body = JSON.stringify(options.body); } }
    if (!isPublic) { if (!jsVarExists("neoGlobalRestEndpointNonce")) { throw new Error("Nonce not found for endpoint call when trying to fetch " + path + ". Are you using a protected endpoint in the frontend as a non-admin?"); } fetchEndpoint.nonce ??= jsVar("neoGlobalRestEndpointNonce"); }
    if (!isPublic) { options.headers ??= {}; options.headers["X-WP-Nonce"] = fetchEndpoint.nonce; }
    const resp = await fetch(url, options);
    if (!options.suppressHttpCodeError && !resp.ok) {
        await extractJson(resp);
    }
    return resp;
}


if (jsVarExists("neoGlobalRestEndpointNonce")) {
    setInterval(async () => {
        fetchEndpoint.nonce = (await fetchEndpoint("/wp-json/neo/refresh-nonce-neo-library-full", { method: "GET" }).then(extractJson)).nonce;
    }, (1) * 60 * 60 * 1000);
}
