package com.jeeplus.auth.config;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Data
@Component
@ConfigurationProperties(prefix = "dingtalk")
public class DingTalkProperties {

    private String defaultTenantId = "10009";

    private String corpId;

    private String agentId;

    private String appKey;

    private String apiKey;

    private String appSecret;

    private Map<String, TenantConfig> tenants = new HashMap<>();

    public TenantConfig getRequiredConfig(String tenantId) {
        String resolvedTenantId = StringUtils.defaultIfBlank(tenantId, defaultTenantId);
        TenantConfig tenantConfig = tenants.get(resolvedTenantId);
        if (tenantConfig == null && tenants.size() == 1) {
            tenantConfig = tenants.values().iterator().next();
        }
        if (tenantConfig == null && StringUtils.isNotBlank(getResolvedAppKey()) && StringUtils.isNotBlank(appSecret)) {
            tenantConfig = new TenantConfig();
            tenantConfig.setCorpId(corpId);
            tenantConfig.setAgentId(agentId);
            tenantConfig.setAppKey(getResolvedAppKey());
            tenantConfig.setAppSecret(appSecret);
        }
        if (tenantConfig == null || StringUtils.isBlank(tenantConfig.getResolvedAppKey()) || StringUtils.isBlank(tenantConfig.getAppSecret())) {
            throw new IllegalStateException("DingTalk config is missing for tenant " + resolvedTenantId);
        }
        return tenantConfig;
    }

    private String getResolvedAppKey() {
        return StringUtils.defaultIfBlank(appKey, apiKey);
    }

    @Data
    public static class TenantConfig {
        private String corpId;
        private String agentId;
        private String appKey;
        private String apiKey;
        private String appSecret;

        public String getResolvedAppKey() {
            return StringUtils.defaultIfBlank(appKey, apiKey);
        }
    }
}
