import { crawlMultiple, findSitemap } from "@devowl-wp/sitemap-crawler";

import { __ } from "../../utils/i18n.js";

import type { Dispatch, SetStateAction } from "react";

type ScanFromSitemapStep = "idle" | "find-sitemap" | "collect-sitemap" | "add-to-queue" | "done";

async function crawlSitemap(setStep?: Dispatch<SetStateAction<ScanFromSitemapStep>>) {
    const textOfferSupport = __(
        'If you think a sitemap exists but you get this error, please <a href="%s" target="_blank" />contact our support</a> and we will look individually where the problem is in your WordPress installation.',
        __("https://devowl.io/support/"),
    );

    // Use original `home_url` to support WordPress installations within a subfolder (https://git.io/JRM9g)
    let rootUrl = (window as any).realCookieBannerQueue.originalHomeUrl as string;
    const blogId = (window as any).realCookieBannerQueue.blogId as number;
    [rootUrl] = rootUrl.split("?", 2);

    setStep?.("find-sitemap");
    const sitemapUrls = await findSitemap(
        rootUrl,
        "rcb-force-sitemap",
        ["?sitemap=index&rcb-force-sitemap=1"],
        `${blogId}`,
    );
    if (sitemapUrls === false) {
        throw new Error(
            `${__(
                "We didn't find a sitemap on your website. We need it to scan all the subpages of your website. Do you have this feature disabled in your WordPress?",
            )} ${textOfferSupport}`,
        );
    }

    setStep?.("collect-sitemap");

    let sites: string[] = [];
    try {
        sites = await crawlMultiple(rootUrl, sitemapUrls);
    } catch (e) {
        throw new Error(
            `${__(
                "The sitemap could not be parsed. Therefore, we cannot check for services on your website.",
            )} ${textOfferSupport}`,
        );
    }

    if (sites.length === 0) {
        throw new Error(
            `${__("The sitemap is empty. So, we could not add any URLs to the scanner.")} ${textOfferSupport}`,
        );
    }

    return sites;
}

export { crawlSitemap, type ScanFromSitemapStep };
