import type { ClientJobEvent } from "@devowl-wp/real-queue";
import { CLIENT_JOB_EVENT_PREFIX, fetchStatus, refreshQueue } from "@devowl-wp/real-queue";
import { commonRequest } from "@devowl-wp/utils";

import { crawlSitemap } from "./crawlSitemap.js";
import { AUTOMATIC_SCAN_STATER_QUEUE_JOB } from "../../types/queue.js";
import { locationRestScannerQueuePost } from "../../wp-api/scannerQueue.post.js";

import type { AutomaticScanStarterQueueJobData } from "../../types/queue.js";
import type {
    ParamsRouteScannerQueuePost,
    RequestRouteScannerQueuePost,
    ResponseRouteScannerQueuePost,
} from "../../wp-api/scannerQueue.post.js";

/**
 * Add listener for the automatic scan starter.
 */
function listenAutomaticScanStarterJobExecution() {
    document.addEventListener(`${CLIENT_JOB_EVENT_PREFIX}${AUTOMATIC_SCAN_STATER_QUEUE_JOB}`, (async ({
        detail: {
            job: { id, process_total },
            resolve,
            // reject,
            saveJobResult,
        },
    }: CustomEvent<ClientJobEvent<AutomaticScanStarterQueueJobData>>) => {
        // Hide scan button in scanner tab
        let scanButton: HTMLElement;

        // Periodically check for the scan button and hide it
        const interval = setInterval(() => {
            scanButton = document.getElementById("rcb-btn-scan-start");
            if (scanButton) {
                scanButton.style.display = "none";
            }
        }, 1000);

        try {
            const sites = await crawlSitemap();

            // Hacky get the REST options for `@devowl-wp/real-queue` as we have not
            // RCB options available on all pages
            const { restRoot, restNonce, restQuery } = (window as any)["realQueue"];
            const restNamespace = "real-cookie-banner/v1";
            const options: any = { restRoot, restNamespace, restNonce, restQuery };

            await commonRequest<
                RequestRouteScannerQueuePost,
                ParamsRouteScannerQueuePost,
                ResponseRouteScannerQueuePost
            >({
                location: locationRestScannerQueuePost,
                options,
                request: {
                    urls: sites,
                    purgeUnused: true,
                },
            });

            await refreshQueue();
            fetchStatus(true);
        } catch (e) {
            // reject({ code: "rcb_sitemap_crawl", message: e.message }); // See below
        } finally {
            clearInterval(interval);
            if (scanButton) {
                scanButton.style.removeProperty("display");
            }

            // Currently, we do not care about errors for the automatic starter
            await saveJobResult(id, process_total);
            resolve();
        }
    }) as any);
}

export { listenAutomaticScanStarterJobExecution };
