import * as API from "./api";
import { getConfig } from "./config";
function normalizeValue(value) {
    if (Array.isArray(value)) {
        return value.join("");
    }
    return typeof value === "string" ? value : undefined;
}
function normalizeToken(value) {
    const normalized = normalizeValue(value)
        ?.replace(/^Bearer\s+/i, "")
        .trim();
    return normalized || undefined;
}
function normalizePath(value) {
    if (Array.isArray(value)) {
        const joined = value.join("/");
        return joined ? `/${joined.replace(/^\/+/, "")}` : undefined;
    }
    if (typeof value !== "string" || value.length === 0) {
        return undefined;
    }
    return value.startsWith("/") ? value : `/${value}`;
}
function readBody(req) {
    if (!req.body)
        return {};
    if (typeof req.body === "string") {
        try {
            return JSON.parse(req.body);
        }
        catch {
            return {};
        }
    }
    return typeof req.body === "object"
        ? req.body
        : {};
}
export default async function revalidate(req, res) {
    try {
        const { edenApi, site } = getConfig();
        const body = readBody(req);
        const token = normalizeToken(req.headers?.authorization || body.token || req.query.token);
        const path = normalizePath(body.path || req.query.path);
        const lang = normalizeValue(body.lang || req.query.lang);
        const all = normalizeValue(body.all || req.query.all);
        if (!token) {
            return res.status(403).send({ error: "no token provided" });
        }
        const { message } = await API.checkToken(edenApi, token);
        if (message !== "token-valid") {
            return res.status(403).send({ error: "invalid token" });
        }
        if (all) {
            if (!lang) {
                return res.status(400).send({ error: "no lang provided" });
            }
            const exportPathMap = await API.getExportPathMap(edenApi, site, lang);
            const barePaths = Object.keys(exportPathMap);
            const paths = barePaths.map((key) => {
                return key.concat("/").replace("//", "/").replace(`/${lang}`, "");
            });
            for await (const path of paths) {
                await res.revalidate(path);
            }
            return res.send({ status: "revalidated all" });
        }
        if (!path) {
            return res.status(400).send({ error: "no path provided" });
        }
        await res.revalidate(path);
        return res.send({ status: "revalidated" });
    }
    catch (err) {
        console.error(err);
        return res.status(500).send({ error: "server error" });
    }
}
