"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisStateAdapter = void 0;
const ioredis_1 = __importDefault(require("ioredis"));
class RedisStateAdapter {
    constructor(config) {
        this.ttl = 3600;
        this.client = new ioredis_1.default(config);
        this.prefix = 'motia:state';
        if (config.ttl) {
            this.ttl = config.ttl;
        }
    }
    async get(traceId, key) {
        const fullKey = this._makeKey(traceId, key);
        const value = await this.client.get(fullKey);
        return value ? JSON.parse(value) : null;
    }
    async set(traceId, key, value) {
        const fullKey = this._makeKey(traceId, key);
        await this.client.set(fullKey, JSON.stringify(value), 'EX', this.ttl);
    }
    async delete(traceId, key) {
        const fullKey = this._makeKey(traceId, key);
        await this.client.del(fullKey);
    }
    async clear(traceId) {
        const pattern = this._makeKey(traceId, '*');
        const keys = await this.client.keys(pattern);
        if (keys.length > 0) {
            await this.client.del(keys);
        }
    }
    async keys(traceId) {
        const pattern = this._makeKey(traceId, '*');
        const keys = await this.client.keys(pattern);
        return keys.map((key) => key.replace(this._makeKey(traceId, ''), ''));
    }
    async traceIds() {
        const pattern = `${this.prefix}:*`;
        const keys = await this.client.keys(pattern);
        return keys.map((key) => key.split(':')[1]);
    }
    async cleanup() {
        await this.client.quit();
    }
    _makeKey(traceId, key) {
        return `${this.prefix}:${traceId}:${key}`;
    }
}
exports.RedisStateAdapter = RedisStateAdapter;
