/**
 * 非标redis缓存模块
 */

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 };
const prod_defaults = { host: 'r-bp117e21a00ae2e4.redis.rds.aliyuncs.com', port: 6379, password: 'Keytop123', database: 111 };

/**
 * 默认配置可以不写，因为插件会给默认配置，例如：host:127.0.0.1
 */
let defaults = {};

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

/**
 * 实际配置
 */
const ioredisConfig = Object.assign(defaults, getNonStandardApiConfig()?.ioredis,
    {
        maxRetriesPerRequest: 0,
        lazyConnect: true,
        enableOfflineQueue: false
    });

logger.trace(`ioredisConfig:`, ioredisConfig);

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

ioredisInstance.on("error", error => {
    /**
     * 如果服务器连接不上，默认会频繁的发起连接，如果连接失败，会不断发生异常，所以过滤该异常
     */
    if (error.code === 'ECONNREFUSED') return;

    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, typeof value === 'object' ? JSON.stringify(value) : value, 'ex', ex || 60 * 60);
    }
}

export { CacheService }