/**
 * 应用服务模块
 * @date 2022-03
 * @author 何华东
 */

import { logger } from "mslib";
import { Container, Inject, Singleton } from "typescript-ioc";
import { Sync } from "./Decorators";
import { TyExternalApiClient, GetConfigInfoResponse } from "./TyExternalApi";
import { redisClient } from "./IORedisClient";

/**
 * appid 应用服务，属于服务层
 */
@Singleton
export default class AppService {
    @Inject
    tyExternalApiClient: TyExternalApiClient;

    readonly CONFIG_INFO = `${Container.getValue('config.basic.tapdId')}_configInfo`;

    /**
     * 获取应用配置信息，包括已授权车场扩展配置
     * 
     * 缓存优先，同步执行，减少对统一API调用
     * @returns 
     */
    @Sync()
    async getConfigInfo(): Promise<GetConfigInfoResponse> {
        try {
            let value = await redisClient.get(this.CONFIG_INFO);
            if(value !== null) return JSON.parse(value);
        } catch (error) {
            logger.error(error);
        }

        let configInfo = await this.tyExternalApiClient.getConfigInfo();
        
        try {
            await redisClient.set(this.CONFIG_INFO, JSON.stringify(configInfo), 'ex', 60 * 60);
        } catch (error) {
            logger.error(error);
        }

        return configInfo;
    }
}

export { AppService }