import { JOB_DELAY_EVENT_PREFIX } from "../../types/events/jobDelay.js";
import { WINDOW_ACTIVITY_DETECTOR_IS_ACTIVE_KEY } from "../activityDetector.js";

import type { JobDelayEvent } from "../../types/events/jobDelay.js";
import type { Job } from "../../types/job.js";

/**
 * Delay a job with the defined `delay_ms`.
 */
function jobDelay(job: Job) {
    const isIdle = !!window[WINDOW_ACTIVITY_DETECTOR_IS_ACTIVE_KEY];
    const { type, delay_ms } = job;
    const settings = {
        delay_ms,
    };

    document.dispatchEvent(
        new CustomEvent<JobDelayEvent>(`${JOB_DELAY_EVENT_PREFIX}${type}`, {
            detail: {
                job,
                isIdle,
                settings,
            },
        }),
    );

    return new Promise<void>((resolve) => setTimeout(resolve, settings.delay_ms));
}

export { jobDelay };
