/**
 * 
 */

import { logger } from "mslib";
import { Singleton } from "typescript-ioc";
import { getBasicConfig, getNonStandardApiConfig } from "./Config";
import Contants from "./Contants";
const IORedis = require("ioredis");

const test_defaults = { host: 'r-bp1qmwd11yi1ujmfbq.redis.rds.aliyuncs.com', port: 6379, password: 'Keytop123', database: 50, maxRetriesPerRequest: 0, lazyConnect: true };
const prod_defaults = { host: 'r-bp117e21a00ae2e4.redis.rds.aliyuncs.com', port: 6379, password: 'Keytop123', database: 111, maxRetriesPerRequest: 0, lazyConnect: true };

let defaults = { maxRetriesPerRequest: 0, lazyConnect: true };

if (Contants.IS_PROD) defaults = prod_defaults;
else if (Contants.IS_TEST) defaults = test_defaults;

/**
 * 非标缓存运行时ioredis配置
 */
export const ioredisConfig = Object.assign(defaults, getNonStandardApiConfig()?.ioredis);

logger.info(`ioredisConfig:${JSON.stringify(ioredisConfig)}`);

/**
 * ioredis 实例
 */
export const ioredisInstance = new IORedis(ioredisConfig);

ioredisInstance.on("error", error => {
    logger.error(error);
});

/**
 * 缓存键管理
 */
export class CacheKey {
    /**
     * app已授权车场配置信息key
     */
    static readonly CONFIG_INFO = `${getBasicConfig().tapdId}_configInfo`;
}

/**
 * 中台项目缓存服务
 */
@Singleton
export default class CacheService {
    async getConfigInfo() {
        return await ioredisInstance.get(CacheKey.CONFIG_INFO);
    }

    async setConfigInfo(value, ex?: number) {
        return await ioredisInstance.set(CacheKey.CONFIG_INFO, JSON.stringify(value), 'ex', ex || 60 * 60);
    }
}

export { CacheService }