const KNOWN_FILENAMES = [
    "sitemap.xml",
    "sitemap_index.xml",
    "sitemap-index.xml",
    "sitemap/",
    "post-sitemap.xml",
    "sitemap/sitemap.xml",
    "sitemap/index.xml",
    "sitemapindex.xml",
    "sitemap.php",
    "sitemap.txt",
    "index.php/sitemap_index.xml",
    "index.php?xml_sitemap=params=",
    "glossar/sitemap.xml",
];

/**
 * Look known sitemap URLs when it is not yet filled in the `robots.txt`.
 *
 * @see https://pagedart.com/blog/how-to-find-the-sitemap-of-a-website/#manually
 */
async function findByKnownFilenames(root: string, tryKnownFilenames = KNOWN_FILENAMES) {
    const promises = tryKnownFilenames.map((filename) =>
        fetch(`${root}${filename}`, {
            // Do not throw an error for failed CORS requests, instead we expect an empty response
            mode: "no-cors",
        }),
    );

    for (const promise of promises) {
        try {
            const response = await promise;
            const responseBody = await response.text();

            // We do not rely on `fetch.ok` cause e.g. RankMath forces `404` error code even the sitemap is rendered
            if (responseBody.indexOf("<sitemapindex") > -1 || responseBody.indexOf("<urlset") > -1) {
                return response.url;
            }
        } catch (e) {
            // Silence is golden.
        }
    }
    return false;
}

export { findByKnownFilenames };
