"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisHostedDemoSessionStore = exports.InMemoryHostedDemoSessionStore = void 0;
const redis_1 = require("redis");
const logger_1 = require("../utils/logger");
const log = (0, logger_1.createLogger)('HostedDemoSessionStore');
class InMemoryHostedDemoSessionStore {
    records = new Map();
    async initialize() {
        return Promise.resolve();
    }
    async loadAll() {
        return [...this.records.entries()].map(([sessionId, value]) => ({
            sessionId,
            value,
        }));
    }
    async set(sessionId, value, _ttlMs) {
        this.records.set(sessionId, value);
    }
    async delete(sessionId) {
        this.records.delete(sessionId);
    }
    async shutdown() {
        this.records.clear();
    }
}
exports.InMemoryHostedDemoSessionStore = InMemoryHostedDemoSessionStore;
class RedisHostedDemoSessionStore {
    client;
    keyPrefix;
    constructor(options) {
        this.client = (0, redis_1.createClient)({ url: options.redisUrl });
        this.keyPrefix = options.keyPrefix;
    }
    async initialize() {
        if (this.client.isOpen) {
            return;
        }
        this.client.on('error', (error) => {
            log.warn('Redis demo session store error:', error);
        });
        await this.client.connect();
    }
    async loadAll() {
        const records = [];
        for await (const keyOrChunk of this.client.scanIterator({
            MATCH: `${this.keyPrefix}:*`,
            COUNT: 100,
        })) {
            const keys = Array.isArray(keyOrChunk) ? keyOrChunk : [keyOrChunk];
            for (const key of keys) {
                const raw = await this.client.get(key);
                if (!raw) {
                    continue;
                }
                const sessionId = key.slice(`${this.keyPrefix}:`.length);
                if (!sessionId) {
                    continue;
                }
                try {
                    const value = JSON.parse(raw);
                    records.push({ sessionId, value });
                }
                catch (error) {
                    log.warn(`Failed to parse demo session payload for ${sessionId}:`, error);
                }
            }
        }
        return records;
    }
    async set(sessionId, value, ttlMs) {
        await this.client.set(this.getKey(sessionId), JSON.stringify(value), {
            PX: ttlMs,
        });
    }
    async delete(sessionId) {
        await this.client.del(this.getKey(sessionId));
    }
    async shutdown() {
        if (this.client.isOpen) {
            await this.client.quit();
        }
    }
    getKey(sessionId) {
        return `${this.keyPrefix}:${sessionId}`;
    }
}
exports.RedisHostedDemoSessionStore = RedisHostedDemoSessionStore;
//# sourceMappingURL=HostedDemoSessionStore.js.map