package com.seer.teach.pay.admin.pay.util;

import com.seer.teach.common.utils.AESUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付配置字段加密/解密工具
 * 用于对支付渠道配置中的敏感字段进行加解密（基于 AESUtils）
 */
@Slf4j
public class PayConfigEncryptUtils {

    /**
     * 需要加密的敏感字段（支持微信、支付宝）
     */
    private static final List<String> SENSITIVE_FIELDS = Arrays.asList(
            // 微信相关
            "appId", "mchId", "mchKey", "secret", "apiV3Key",
            "merchantSerialNumber", "publicKeyPem", "privateKeyPem",
            // 支付宝相关
            "appPrivateKey", "alipayPublicKey", "appCertPath", "alipayCertPath"
    );

    /**
     * 加密配置参数
     */
    public static Map<String, String> encryptConfig(Map<String, String> configMap) {
        if (configMap == null || configMap.isEmpty()) return configMap;

        Map<String, String> encryptedMap = new LinkedHashMap<>();

        for (Map.Entry<String, String> entry : configMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            if (SENSITIVE_FIELDS.contains(key) && value != null && !value.isEmpty()) {
                try {
                    String encrypted = AESUtils.encrypt(value);
                    encryptedMap.put(key, encrypted);
                    log.debug("字段 [{}] 加密成功", key);
                } catch (Exception e) {
                    log.error("字段 [{}] 加密失败: {}", key, e.getMessage(), e);
                    encryptedMap.put(key, value);
                }
            } else {
                encryptedMap.put(key, value);
            }
        }

        return encryptedMap;
    }

    /**
     * 解密配置参数
     */
    public static Map<String, String> decryptConfig(Map<String, String> configMap) {
        if (configMap == null || configMap.isEmpty()) return configMap;

        Map<String, String> decryptedMap = new LinkedHashMap<>();

        for (Map.Entry<String, String> entry : configMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            if (SENSITIVE_FIELDS.contains(key) && value != null && !value.isEmpty()) {
                try {
                    String decrypted = AESUtils.decrypt(value);
                    decryptedMap.put(key, decrypted);
                } catch (Exception e) {
                    log.error("字段 [{}] 解密失败: {}", key, e.getMessage(), e);
                    decryptedMap.put(key, value);
                }
            } else {
                decryptedMap.put(key, value);
            }
        }

        return decryptedMap;
    }
}
