import { getConfig } from "./config";
import * as API from "./api";
export default async function sitemap() {
    const { edenApi, site, langs, domains, preProd } = getConfig();
    if (preProd === true) {
        return [];
    }
    let langsNotInPreprod = langs;
    if (Array.isArray(preProd)) {
        langsNotInPreprod = langs.reduce((acc, lang) => {
            if (preProd.includes(lang)) {
                return acc;
            }
            return [...acc, lang];
        }, []);
    }
    const exportPathMap = await API.getExportPathMap(edenApi, site, langsNotInPreprod.join(","), false);
    const barePaths = Object.keys(exportPathMap);
    const paths = await Promise.all(barePaths.map(async (key) => {
        const [locale, ...rest] = key.substring(1).split("/");
        const path = "/".concat(rest.join("/")).replace("//", "/");
        const { priority, frequency, inSitemap, last_updated } = await API.getSeo(edenApi, site, locale, path);
        return {
            locale,
            priority: getPriority(priority, path),
            frequency: frequency || "Always",
            inSitemap: inSitemap ?? true,
            lastUpdated: last_updated,
            path,
        };
    }));
    const filteredPaths = paths.filter((path) => path?.inSitemap);
    return filteredPaths.map((item) => {
        const { locale, priority, frequency, path, lastUpdated } = item;
        const domain = domains[locale];
        const url = `https://${domain}${path}`;
        return {
            url,
            lastModified: new Date(lastUpdated),
            changeFrequency: frequency,
            priority: priority,
        };
    });
}
function getPriority(priority, url) {
    if (priority) {
        return priority;
    }
    return (100 - (url.split("/").length - 2) * 10) / 100;
}
