/**
 * 应用服务模块
 * @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;

    /**
     * 获取应用配置信息，包括已授权车场扩展配置
     * 
     * 缓存优先，同步执行，减少对统一API调用
     * @returns 
     */
    @Sync()
    async getConfigInfo(): Promise<GetConfigInfoResponse> {
        let tapdId = Container.getValue('config.basic.tapdId');
        if (!tapdId) throw new Error('未配置tapdId');

        let configInfo = null;
        let configInfo_key = `${tapdId}_configInfo`;

        try {
            await redisClient.get(configInfo_key);
        } catch (error) {
            logger.error(error);
        }

        if (!configInfo) {
            configInfo = await this.tyExternalApiClient.getConfigInfo();

            try {
                await redisClient.set(configInfo_key, JSON.stringify(configInfo), 'ex', 60 * 60);
            } catch (error) {
                logger.error(error);
            }
        }

        return configInfo;
    }
}

export { AppService }