import { snackbar } from "../user-interface/common/eden-snackbar.js";
import { saveNavContent } from "./api.js";
import { DUPLICATE_NAME } from "./error.js";
import { fetchNode, fetchRevalidate } from "./fetcher.js";
import t from "../i18n/index.js";
function revalidatePaths(paths) {
    for (const path of paths) {
        fetchRevalidate(path.lang, path.path);
    }
}
function notifyResult(result) {
    if (result === undefined || result.error === undefined) {
        snackbar(t("snackbars.structure-updated"), "success");
        return;
    }
    snackbar(result.error, "error");
}
export async function create(node, name, position, parentId) {
    const result = await saveNavContent("create", {
        tmpId: node.id,
        parentId,
        name,
        position,
    });
    notifyResult(result);
    return result;
}
export async function rename(navItemId, newName) {
    const result = await saveNavContent("rename", { navItemId, newName });
    if (result === undefined || result.error === undefined) {
        const message = t("snackbars.structure-updated");
        snackbar(message, "success");
        return { message };
    }
    else {
        const error = DUPLICATE_NAME(newName);
        snackbar(error, "error");
        return { error };
    }
}
export async function remove(navItemId, paths) {
    const result = await saveNavContent("remove", { navItemId });
    revalidatePaths(paths);
    notifyResult(result);
}
export async function move(parentId, navItemId, position) {
    const result = await saveNavContent("move", {
        parentId,
        navItemId,
        position,
    });
    notifyResult(result);
}
export async function saveNode(node, paths = []) {
    const result = await saveNavContent("saveNode", node);
    revalidatePaths(paths);
    notifyResult(result);
}
export async function getNode(id) {
    return fetchNode(id);
}
