import { uuidv7 } from "../db/uuidv7.js";
export class SecretInputService {
    pending = new Map();
    defaultTimeoutMs;
    onRequest;
    onResolved;
    constructor(options = {}) {
        this.defaultTimeoutMs = options.defaultTimeoutMs ?? 120_000;
        this.onRequest = options.onRequest;
        this.onResolved = options.onResolved;
    }
    requestSecret(input) {
        const now = new Date();
        const expiresAt = new Date(now.getTime() + (input.timeoutMs ?? this.defaultTimeoutMs));
        const request = {
            id: uuidv7(),
            sessionId: input.sessionId,
            userId: input.userId ?? null,
            title: input.title,
            prompt: input.prompt,
            requestedBy: input.requestedBy ?? null,
            createdAt: now.toISOString(),
            expiresAt: expiresAt.toISOString(),
            status: "pending",
        };
        return new Promise((resolve) => {
            const timer = setTimeout(() => {
                this.resolveRequest(request.id, null, "timeout");
            }, input.timeoutMs ?? this.defaultTimeoutMs);
            this.pending.set(request.id, { request, resolve, timer });
            this.onRequest?.(request);
        });
    }
    listPending(sessionId, userId) {
        return [...this.pending.values()]
            .map((entry) => entry.request)
            .filter((request) => {
            if (sessionId && request.sessionId !== sessionId)
                return false;
            if (userId && request.userId && request.userId !== userId)
                return false;
            return true;
        });
    }
    submit(requestId, value, userId) {
        const entry = this.pending.get(requestId);
        if (!entry)
            return false;
        if (entry.request.userId && userId && entry.request.userId !== userId)
            return false;
        this.resolveRequest(requestId, value, "submitted");
        return true;
    }
    cancel(requestId, userId) {
        const entry = this.pending.get(requestId);
        if (!entry)
            return false;
        if (entry.request.userId && userId && entry.request.userId !== userId)
            return false;
        this.resolveRequest(requestId, null, "cancelled");
        return true;
    }
    resolveRequest(requestId, value, status) {
        const entry = this.pending.get(requestId);
        if (!entry)
            return;
        this.pending.delete(requestId);
        clearTimeout(entry.timer);
        const request = { ...entry.request, status };
        entry.resolve(value);
        this.onResolved?.(request);
    }
}
//# sourceMappingURL=secret-input.js.map