"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHashesWithPattern = exports.deleteKeysWithPattern = exports.deleteObject = exports.findObject = exports.updateObject = exports.createObject = exports.findByContain = exports.clearAllKeys = exports.del = exports.get = exports.getSimple = exports.set = void 0;
const Redis = require("ioredis");
const redis = new Redis(process.env.REDIS_URI);
function set(key, value) {
    return __awaiter(this, void 0, void 0, function* () {
        if (typeof value == "object")
            yield redis.set(key, JSON.stringify(value));
        else {
            yield redis.set(key, value);
        }
    });
}
exports.set = set;
function getSimple(key) {
    return __awaiter(this, void 0, void 0, function* () {
        const value = yield redis.get(key);
        return value;
    });
}
exports.getSimple = getSimple;
function get({ key, value, parse }) {
    return __awaiter(this, void 0, void 0, function* () {
        if (key.includes("*")) {
            const keys = yield redis.keys(key);
            if (keys.length > 0) {
                if (value) {
                    for (const key of keys) {
                        const val = yield redis.get(key);
                        if (val.includes(value)) {
                            if (parse)
                                return JSON.parse(val);
                            return val;
                        }
                    }
                }
                else {
                    let res = [];
                    for (const key of keys) {
                        const val = yield redis.get(key);
                        if (parse)
                            res.push(JSON.parse(val));
                        res.push(val);
                    }
                    return res;
                }
            }
            return null;
        }
        else {
            const value = yield redis.get(key);
            if (parse)
                return JSON.parse(value);
            return value;
        }
    });
}
exports.get = get;
function del(key) {
    return __awaiter(this, void 0, void 0, function* () {
        yield redis.del(key);
    });
}
exports.del = del;
function clearAllKeys(...keys) {
    return __awaiter(this, void 0, void 0, function* () {
        for (const key of keys) {
            // Retrieve all keys matching the pattern '*'
            const del_keys = yield redis.keys(key);
            // If there are keys, delete them
            if (del_keys.length > 0) {
                // console.log("del_keys: ", del_keys);
                yield redis.del(...del_keys);
            }
        }
    });
}
exports.clearAllKeys = clearAllKeys;
function findByContain(key, keyName, substring) {
    var _a, _b, _c;
    return __awaiter(this, void 0, void 0, function* () {
        // const keys = await redis.keys("*" + substring + "*");
        // const keys = await redis.keys("user:*");
        const keys = yield redis.keys(key);
        const results = [];
        for (const key of keys) {
            const value = yield redis.get(key);
            if (value) {
                const obj = JSON.parse(value);
                if ((_a = substring === null || substring === void 0 ? void 0 : substring.trim()) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes((_c = (_b = obj[keyName]) === null || _b === void 0 ? void 0 : _b.trim()) === null || _c === void 0 ? void 0 : _c.toLowerCase())) {
                    results.push(obj);
                }
            }
        }
        return results;
    });
}
exports.findByContain = findByContain;
function createObject({ whatsappId, contactId, identifier, value, history = "" }) {
    return __awaiter(this, void 0, void 0, function* () {
        const key = `whatsappId:${whatsappId}:contactId:${contactId}:identifier:${identifier}`;
        const result = yield redis.hmset(key, "whatsappId", whatsappId, "contactId", contactId, "identifier", identifier, "value", value, "history", history);
        yield redis.expire(key, 300);
    });
}
exports.createObject = createObject;
function updateObject({ whatsappId, contactId, identifier, value }) {
    return __awaiter(this, void 0, void 0, function* () {
        const key = `whatsappId:${whatsappId}:contactId:${contactId}:identifier:${identifier}`;
        yield redis.hset(key, "value", value);
    });
}
exports.updateObject = updateObject;
function findObject(whatsappId, contactId, identifier) {
    return __awaiter(this, void 0, void 0, function* () {
        const key = `whatsappId:${whatsappId}:contactId:${contactId}:identifier:${identifier}`;
        const result = yield redis.hmget(key, "whatsappId", "contactId", "identifier", "value", "history");
        return result;
    });
}
exports.findObject = findObject;
function deleteObject(whatsappId, contactId, identifier) {
    return __awaiter(this, void 0, void 0, function* () {
        const key = `whatsappId:${whatsappId}:contactId:${contactId}:identifier:${identifier}`;
        const deletedCount = yield redis.del(key);
    });
}
exports.deleteObject = deleteObject;
function deleteKeysWithPattern(whatsappId, contactId) {
    return __awaiter(this, void 0, void 0, function* () {
        const pattern = `whatsappId:${whatsappId}:contactId:${contactId}:*`;
        let cursor = "0";
        do {
            const [newCursor, keys] = yield redis.scan(cursor, "MATCH", pattern, "COUNT", "100");
            for (const key of keys) {
                yield redis.del(key);
            }
            cursor = newCursor;
        } while (cursor !== "0");
    });
}
exports.deleteKeysWithPattern = deleteKeysWithPattern;
function getHashesWithPattern(whatsappId, contactId) {
    return __awaiter(this, void 0, void 0, function* () {
        const pattern = `whatsappId:${whatsappId}:contactId:${contactId}:*`;
        let cursor = "0";
        const hashes = [];
        do {
            const [newCursor, keys] = yield redis.scan(cursor, "MATCH", pattern, "COUNT", "100");
            for (const key of keys) {
                const hash = yield redis.hgetall(key);
                hashes.push(hash);
            }
            cursor = newCursor;
        } while (cursor !== "0");
        return hashes;
    });
}
exports.getHashesWithPattern = getHashesWithPattern;
