"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeepAliveService = void 0;
/**
 * Sends periodic HTTP requests to a public URL to prevent the hosting platform
 * (Render, Railway, Heroku, etc.) from putting the service to sleep after a
 * period of inactivity.
 *
 * Self-pinging helps, but an external uptime monitor (UptimeRobot, cron-job.org,
 * Pingdom, etc.) is the most reliable way to keep a free-tier web service awake.
 */
class KeepAliveService {
    url;
    intervalMs;
    requestTimeoutMs;
    logger;
    timer;
    isRunning;
    constructor(options) {
        this.url = options.url;
        this.intervalMs = options.intervalMs ?? 10 * 60 * 1000; // 10 minutes
        this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
        this.logger = options.logger;
        this.isRunning = false;
        if (this.intervalMs < 60_000) {
            this.logger.warn(`Keep-alive interval is very short (${this.intervalMs}ms). Consider increasing it to avoid excessive requests.`, { url: this.url });
        }
    }
    start() {
        if (this.isRunning)
            return;
        this.isRunning = true;
        this.logger.info("Starting keep-alive service.", {
            url: this.url,
            intervalMs: this.intervalMs
        });
        // Ping immediately so the service is woken up on startup if it was sleeping,
        // then continue pinging at the configured interval.
        void this.ping();
        this.timer = setInterval(() => void this.ping(), this.intervalMs);
        this.timer.unref?.();
    }
    stop() {
        if (!this.isRunning)
            return;
        this.isRunning = false;
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = undefined;
        }
        this.logger.info("Keep-alive service stopped.");
    }
    async ping() {
        const startTime = Date.now();
        try {
            const controller = new AbortController();
            const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);
            const response = await fetch(this.url, {
                method: "GET",
                signal: controller.signal,
                headers: { "User-Agent": "alpha-pulse-keepalive/1.0" }
            });
            clearTimeout(timeout);
            const durationMs = Date.now() - startTime;
            this.logger.debug("Keep-alive ping completed.", {
                url: this.url,
                status: response.status,
                durationMs
            });
        }
        catch (error) {
            const durationMs = Date.now() - startTime;
            this.logger.error("Keep-alive ping failed. The service may go to sleep if the hosting platform detects inactivity.", {
                url: this.url,
                durationMs,
                error: error instanceof Error ? error.message : String(error)
            });
        }
    }
}
exports.KeepAliveService = KeepAliveService;
