import { getAgentState } from "./state.js";
import { generateToken } from "../obs/token.js";
function normalizeTtlMinutes(value) {
    if (typeof value !== "number" || !Number.isFinite(value))
        return 30;
    return Math.max(5, Math.min(480, Math.floor(value)));
}
function normalizeReason(value) {
    if (typeof value !== "string" || !value.trim())
        return "Requested from admin Remote Access";
    return value.trim().slice(0, 200);
}
export const createRdpSessionHandler = () => {
    return (_commandId, payload) => {
        let tunnelUrl;
        try {
            tunnelUrl = getAgentState().consoleUrl;
        }
        catch {
            // AgentState not yet initialized.
        }
        if (!tunnelUrl) {
            return Promise.resolve({
                status: "failed",
                result: JSON.stringify({
                    error: "Remote desktop is unavailable: consoleUrl/tunnel URL is not set",
                }),
            });
        }
        const body = (payload && typeof payload === "object") ? payload : {};
        const ttlMinutes = normalizeTtlMinutes(body.ttlMinutes);
        const reason = normalizeReason(body.reason);
        const { token, expiresAt } = generateToken(ttlMinutes, reason);
        const baseUrl = tunnelUrl.replace(/\/(obs|console)(\/.*)?$/, "").replace(/\/$/, "");
        const url = `${baseUrl}/rdp/${token}`;
        return Promise.resolve({
            status: "completed",
            result: JSON.stringify({
                url,
                expiresAt,
                ttlMinutes,
            }),
        });
    };
};
//# sourceMappingURL=rdp-session-command.js.map