import { JOBS_RETRIED_EVENT } from "../../types/events/jobsRetried.js";
import { request as utilsRequest } from "../../utils/request.js";
import { locationRestJobsRetryPost } from "../../wp-api/jobsRetry.post.js";
import { fetchStatus } from "../fetchStatus.js";

import type { JobsRetriedEvent } from "../../types/events/jobsRetried.js";
import type {
    ParamsRouteJobsRetryPost,
    RequestRouteJobsRetryPost,
    ResponseRouteJobsRetryPost,
} from "../../wp-api/jobsRetry.post.js";

/**
 * Retry jobs by e.g. type. This is similar to a "Cancel" button.
 */
async function retryJobs(request: RequestRouteJobsRetryPost) {
    const response = await utilsRequest<
        RequestRouteJobsRetryPost,
        ParamsRouteJobsRetryPost,
        ResponseRouteJobsRetryPost
    >({
        location: locationRestJobsRetryPost,
        request,
    });

    document.dispatchEvent(
        new CustomEvent<JobsRetriedEvent>(JOBS_RETRIED_EVENT, {
            detail: {
                request,
                response,
            },
        }),
    );

    await fetchStatus(true);
}

export { retryJobs };
