import { errors } from "./error.js";
import { isLocalhost } from "./util.js";
import { getRuntimeConfig, getRuntimeEden } from "./runtime.js";
function fetcher(host, method = "GET") {
    return async (url, { resultType = "text", headers, body, formData = false } = {}) => {
        try {
            const response = await fetch(`${host}${url}`, {
                method,
                headers,
                body: formData
                    ? body
                    : method !== "GET"
                        ? JSON.stringify(body)
                        : undefined,
            });
            if (response.ok) {
                return resultType === "text"
                    ? await response.text()
                    : await response.json();
            }
            else {
                throw errors[response.status] || errors["500"];
            }
        }
        catch (e) {
            if (isLocalhost()) {
                console.info("error", e);
            }
            return { error: e };
        }
    };
}
const fetchRelativeGet = fetcher("");
const fetchRelativePost = fetcher("", "POST");
const fetchApiPost = (url, options) => fetcher(getRuntimeConfig().edenApi, "POST")(url, options);
const fetchApiGet = (url, options) => fetcher(getRuntimeConfig().edenApi)(url, options);
function getToken() {
    return window.sessionStorage.getItem("eden_token");
}
function withAuthHeaders(headers = {}) {
    const token = getToken();
    return token ? { ...headers, authorization: token } : headers;
}
function isLangPrefixEnabled(langPrefix) {
    return Boolean(langPrefix);
}
function serializeLangPrefix(langPrefix) {
    return String(isLangPrefixEnabled(langPrefix));
}
export function fetchFormats() {
    const { templates } = getRuntimeConfig();
    return fetchRelativeGet(templates, {
        resultType: "text",
    });
}
export async function fetchRevalidateAll(lang) {
    const { langs, langPrefix, domains } = getRuntimeConfig();
    const { default: EdenRevalidationIndicator } = await import("../user-interface/page/eden-revalidation-indicator.js");
    const revalidationIndicator = new EdenRevalidationIndicator();
    revalidationIndicator.init();
    if (isLangPrefixEnabled(langPrefix) || isLocalhost()) {
        const locale = lang || langs.join(",");
        await fetchRelativePost(`/api/revalidate/`, {
            resultType: "json",
            headers: withAuthHeaders({ "Content-Type": "application/json" }),
            body: { all: true, lang: locale },
        });
    }
    else {
        for await (const locale of langs) {
            const domain = domains[locale];
            if (domain) {
                await fetcher(`https://${domain}`, "POST")(`/api/revalidate/`, {
                    resultType: "json",
                    headers: withAuthHeaders({ "Content-Type": "application/json" }),
                    body: { all: true, lang: locale },
                });
            }
        }
    }
    revalidationIndicator.done();
}
export function fetchRevalidate(lang, path) {
    const { lang: currentLang, domains } = getRuntimeConfig();
    if (lang === currentLang) {
        return fetchRelativePost(`/api/revalidate/`, {
            resultType: "json",
            headers: withAuthHeaders({ "Content-Type": "application/json" }),
            body: { path },
        });
    }
    const domain = domains[lang];
    return fetcher(`https://${domain}`, "POST")(`/api/revalidate/`, {
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: { path },
    });
}
export function sendRevalidateAllBeacon(lang) {
    const token = getToken();
    const { langs, langPrefix, domains } = getRuntimeConfig();
    const locale = lang || langs.join(",");
    const payload = new Blob([JSON.stringify({ all: true, lang: locale, token })], {
        type: "application/json",
    });
    if (lang || isLangPrefixEnabled(langPrefix) || isLocalhost()) {
        navigator.sendBeacon(`/api/revalidate/`, payload);
    }
    else {
        for (const locale of langs) {
            const domain = domains[locale];
            if (domain) {
                navigator.sendBeacon(`https://${domain}/api/revalidate/`, payload);
            }
        }
    }
}
export function fetchStructure(path, lang, langPrefix) {
    const { site } = getRuntimeConfig();
    return fetchApiGet(`/api/admin/structure?path=${path}&lang=${lang}&site=${site}&langPrefix=${serializeLangPrefix(langPrefix)}`, {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
    });
}
export function fetchClearCache() {
    const { site } = getRuntimeConfig();
    return fetchApiGet(`/api/clear-cache?site=${site}`, {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
    });
}
export function fetchNode(id) {
    const { site } = getRuntimeConfig();
    return fetchApiGet(`/api/admin/structure/node?navItemId=${id}&site=${site}`, {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
    });
}
export function fetchNodeCreation(node) {
    const { site } = getRuntimeConfig();
    const { email } = getRuntimeEden().user;
    return fetchApiPost("/api/admin/structure/create-node", {
        resultType: "json",
        headers: {
            ...withAuthHeaders({ "Content-Type": "application/json" }),
        },
        body: { site, node, user: email },
    });
}
export function fetchNodeUpdate(node) {
    const { site } = getRuntimeConfig();
    const { email } = getRuntimeEden().user;
    return fetchApiPost("/api/admin/structure/save-node", {
        resultType: "json",
        headers: {
            ...withAuthHeaders({ "Content-Type": "application/json" }),
        },
        body: { site, node, user: email },
    });
}
export function fetchNodeMove(node) {
    const { site } = getRuntimeConfig();
    const { email } = getRuntimeEden().user;
    return fetchApiPost("/api/admin/structure/move-node", {
        resultType: "json",
        headers: {
            ...withAuthHeaders({ "Content-Type": "application/json" }),
        },
        body: { site, node, user: email },
    });
}
export function fetchNodeRemoval(node) {
    const { site } = getRuntimeConfig();
    const { email } = getRuntimeEden().user;
    return fetchApiPost("/api/admin/structure/remove-node", {
        resultType: "json",
        headers: {
            ...withAuthHeaders({ "Content-Type": "application/json" }),
        },
        body: { site, node, user: email },
    });
}
export function fetchNodeRename(node) {
    const { site } = getRuntimeConfig();
    const { email } = getRuntimeEden().user;
    return fetchApiPost("/api/admin/structure/rename-node", {
        resultType: "json",
        headers: {
            ...withAuthHeaders({ "Content-Type": "application/json" }),
        },
        body: { site, node, user: email },
    });
}
export function fetchContentSave(lang, path, editors, startedAt) {
    const { email: user } = getRuntimeEden().user;
    const { site, edenMode, langPrefix } = getRuntimeConfig();
    const langPrefixEnabled = isLangPrefixEnabled(langPrefix);
    return fetchApiPost("/api/admin/content/save", {
        resultType: "json",
        headers: {
            ...withAuthHeaders({ "Content-Type": "application/json" }),
        },
        body: {
            edenMode,
            site,
            lang,
            path,
            zones: editors,
            langPrefix: langPrefixEnabled,
            user,
            startedAt,
        },
    });
}
export function fetchLastUpdated(lang, langPrefix, path) {
    const { site } = getRuntimeConfig();
    const langPrefixEnabled = isLangPrefixEnabled(langPrefix);
    return fetchApiPost(`/api/admin/content/get-last-updated`, {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: { site, lang, langPrefix: langPrefixEnabled, path },
    });
}
export function fetchTimestamp() {
    return fetchApiGet(`/api/admin/timestamp`, {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
    });
}
export const FILE_MANAGER_EXTENSIONS = ["jpg", "jpeg", "png"];
export function fetchFileManagerList(path) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/list", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            path,
            extensions: FILE_MANAGER_EXTENSIONS,
        },
    });
}
export function fetchFileManagerStorageStats() {
    const { site } = getRuntimeConfig();
    return fetchApiGet(`/api/files/storage/${site}`, {
        resultType: "json",
        headers: withAuthHeaders(),
    });
}
export function createFileManagerFolder(name, path) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/createDir", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            name,
            path,
            extensions: FILE_MANAGER_EXTENSIONS,
        },
    });
}
export function removeFileManagerItem(path, paths) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/remove", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            path,
            paths,
            extensions: FILE_MANAGER_EXTENSIONS,
        },
    });
}
export function renameFileManagerItem(file, name) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/rename", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            file,
            name,
            extensions: FILE_MANAGER_EXTENSIONS,
        },
    });
}
export function cropFileManagerItem(path, left, top, width, height, targetWidth, targetHeight, only) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/crop", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            path,
            left,
            top,
            width,
            height,
            targetWidth,
            targetHeight,
            only,
        },
    });
}
export function moveFileManagerItem(path, paths, target) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/move", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            path,
            paths,
            target,
            extensions: FILE_MANAGER_EXTENSIONS,
        },
    });
}
export function fileManagerMoveList(paths) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/moveList", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            paths,
        },
    });
}
export function rotateFileManagerImage(path) {
    const { site } = getRuntimeConfig();
    return fetchApiPost("/api/files/rotate", {
        resultType: "json",
        headers: withAuthHeaders({ "Content-Type": "application/json" }),
        body: {
            site,
            path,
            extensions: FILE_MANAGER_EXTENSIONS,
        },
    });
}
export function uploadFileManagerItem(payload) {
    return fetchApiPost("/api/files/upload", {
        resultType: "json",
        headers: withAuthHeaders(),
        body: payload,
        formData: true,
    });
}
