package com.fs.mp.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 本模块独立 WxMpService：只读 mp-silent.wx.*，不使用 fs-service 的 WxMpConfiguration。
 */
@Slf4j
@RequiredArgsConstructor
@Configuration
@EnableConfigurationProperties(MpWxProperties.class)
public class MpWxMpConfiguration {

    private final MpWxProperties properties;

    @Bean
    @Primary
    public WxMpService wxMpService() {
        List<MpWxProperties.MpConfig> configs = this.properties.getConfigs();
        if (configs == null || configs.isEmpty()) {
            throw new IllegalStateException("请在 yml 中配置 mp-silent.wx.configs（appId/secret），与商户 profile 的 wx.mp 无关");
        }
        log.info("[MpWx] 使用本模块独立配置初始化公众号，数量={}", configs.size());
        for (MpWxProperties.MpConfig cfg : configs) {
            log.info("[MpWx] 加载公众号 appId={}, secret={}", cfg.getAppId(), maskSecret(cfg.getSecret()));
        }
        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(configs.stream().map(a -> {
            WxMpDefaultConfigImpl storage = new WxMpDefaultConfigImpl();
            storage.setAppId(a.getAppId());
            storage.setSecret(a.getSecret());
            storage.setToken(a.getToken());
            storage.setAesKey(a.getAesKey());
            return storage;
        }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
        log.info("[MpWx] 本模块 WxMpService 初始化完成");
        return service;
    }

    private String maskSecret(String secret) {
        if (secret == null || secret.isEmpty()) {
            return "(空)";
        }
        if (secret.length() <= 8) {
            return "****";
        }
        return secret.substring(0, 4) + "****" + secret.substring(secret.length() - 4);
    }
}
