import { REMAINING_EVENT } from "../../types/events/remaining.js";
import { getStaticOptions } from "../../utils/options.js";
import { request } from "../../utils/request.js";
import { locationRestJobsGet } from "../../wp-api/jobs.get.js";
import { fetchStatus, getConfigurableStatusParameters } from "../fetchStatus.js";
import { getGlobalQueue } from "../global.js";

import type { RemainingEvent } from "../../types/events/remaining.js";
import type { ParamsRouteJobsGet, RequestRouteJobsGet, ResponseRouteJobsGet } from "../../wp-api/jobs.get.js";
import type { Task } from "../queueClass.js";

/**
 * Fetch the next list of jobs so we can populate to our queue.
 */
function createJobToPopulateNextJobs(afterJobId: number, queueClass = getGlobalQueue()): Task {
    return async () => {
        try {
            const { jobs, remaining, status } = await request<
                RequestRouteJobsGet,
                ParamsRouteJobsGet,
                ResponseRouteJobsGet
            >({
                location: locationRestJobsGet,
                params: {
                    after: afterJobId,
                    ...getConfigurableStatusParameters(),
                },
            });

            getStaticOptions().remaining = remaining;
            fetchStatus({ from: "object", status });

            document.dispatchEvent(
                new CustomEvent<RemainingEvent>(REMAINING_EVENT, {
                    detail: {
                        remaining,
                    },
                }),
            );

            queueClass.enqueueFromList(jobs);
        } catch (e) {
            // Something went wrong between request and WP REST API - we pause the queue here cause
            // we wait for the next refresh of the page - the REST API response is always valid and
            // does not throw any error
            queueClass.handler.pause();
        }
    };
}

export { createJobToPopulateNextJobs };
