package org.shop.crop.service;

import com.tencent.wework.Finance;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class FinanceSdkManager {

    // 存储所有已初始化的 SDK 实例：corpId -> sdk handle
    private final Map<String, Long> sdkMap = new ConcurrentHashMap<>();

    // 存储每个企业的 secret 配置
    private final Map<String, String> secretMap = new ConcurrentHashMap<>();

    /**
     * 初始化一个企业的 SDK 客户端
     */
    public synchronized Long initSdk(String corpId, String secret) {
        if (sdkMap.containsKey(corpId)) {
            return sdkMap.get(corpId); // 已存在，直接返回
        }

        long sdk = Finance.NewSdk();
        int init = Finance.Init(
                sdk,
                corpId,
                secret
        );
        if (init != 0) {
            Finance.DestroySdk(sdk);
            throw new RuntimeException("初始化sdk失败,失败消息为：ret = " + init);
        }

        sdkMap.put(corpId, sdk);
        secretMap.put(corpId, secret);

        System.out.println("✅ SDK initialized for corpId: " + corpId + ", sdk=" + sdk);
        return sdk;
    }

    /**
     * 获取某个企业的 SDK 实例
     */
    public Long getSdk(String corpId) {
        Long sdk = sdkMap.get(corpId);
        if (sdk == null) {
            throw new IllegalArgumentException("No SDK initialized for corpId: " + corpId);
        }
        return sdk;
    }

    /**
     * 销毁某个企业的 SDK 实例
     */
    public synchronized void destroySdk(String corpId) {
        Long sdk = sdkMap.remove(corpId);
        if (sdk != null && sdk > 0) {
            int ret = Finance.DestroySdk(sdk); // 或 Finance.FreeSdk(sdk)
            System.out.println("🔥 SDK destroyed for corpId: " + corpId + ", ret=" + ret);
        }
        secretMap.remove(corpId);
    }


}