import { useCallback } from "react";

import { useProgress } from "@devowl-wp/real-queue";

import { useStores } from "../store/stores.js";
import { SCAN_QUEUE_JOB } from "../types/queue.js";

import type { ScanQueueJobData } from "../types/queue.js";
import type { ResponseRouteScannerResultExternalsGet } from "../wp-api/scannerResultsExternal.get.js";
import type { ResponseRouteScannerResultTemplatesGet } from "../wp-api/scannerResultsTemplate.get.js";

type UseProgressParameters = Parameters<typeof useProgress>[0];

/**
 * Returns the status / progress of the scanner.
 */
function useScannerProgress(
    fetchStatusInterval?: UseProgressParameters["fetchStatusInterval"],
    fetchAdditionalData: false | "rcb-scan-list" | "rcb-scan-notice" = false,
    onCancel?: UseProgressParameters["onCancel"],
) {
    const { scannerStore } = useStores();

    return useProgress<
        ScanQueueJobData,
        {
            "rcb-scan-list": {
                templates: ResponseRouteScannerResultTemplatesGet;
                externalUrls: ResponseRouteScannerResultExternalsGet;
            };
        }
    >({
        type: SCAN_QUEUE_JOB,
        fetchStatusInterval,
        fetchAdditionalData,
        onAdditionalData: useCallback(
            ({ "rcb-scan-list": rcbScanList }) => {
                const { templates, externalUrls } = rcbScanList;
                scannerStore.resultTemplatesFromResponse(templates);
                scannerStore.resultExternalUrlsFromResponse(externalUrls);
            },
            [scannerStore],
        ),
        onCancel,
    });
}

export { useScannerProgress };
