import { JOBS_DELETED_EVENT } from "../../types/events/jobsDeleted.js";
import { request } from "../../utils/request.js";
import { locationRestJobsDelete } from "../../wp-api/jobs.delete.js";
import { fetchStatus } from "../fetchStatus.js";

import type { JobsDeletedEvent } from "../../types/events/jobsDeleted.js";
import type {
    ParamsRouteJobsDelete,
    RequestRouteJobsDelete,
    ResponseRouteJobsDelete,
} from "../../wp-api/jobs.delete.js";

/**
 * Delete jobs by e.g. type. This is similar to a "Cancel" button.
 */
async function deleteJobs(params: ParamsRouteJobsDelete) {
    const response = await request<RequestRouteJobsDelete, ParamsRouteJobsDelete, ResponseRouteJobsDelete>({
        location: locationRestJobsDelete,
        params,
    });

    document.dispatchEvent(
        new CustomEvent<JobsDeletedEvent>(JOBS_DELETED_EVENT, {
            detail: {
                params,
                response,
            },
        }),
    );

    await fetchStatus(true);

    return response;
}

export { deleteJobs };
