package com.sino.mci.channel.wecom.archive;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sino.mci.channel.wecom.archive.model.FinanceMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 企业微信会话存档 Finance SDK 模拟客户端。
 *
 * <p>默认实现，不依赖 JNI/.so 库，返回固定结构的模拟数据，用于开发、联调与单元测试。</p>
 */
@Slf4j
public class MockFinanceSdkClient implements FinanceSdkClient {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private final AtomicLong seqGenerator = new AtomicLong(1000);

    @Override
    public boolean init(String corpId, String secret) {
        log.info("[MockFinanceSdk] init corpId={}, secret=***", corpId);
        return true;
    }

    @Override
    public List<FinanceMessage> getChatData(long seq, int limit) {
        log.info("[MockFinanceSdk] getChatData seq={}, limit={}", seq, limit);
        List<FinanceMessage> messages = new ArrayList<>();
        int count = Math.min(limit, 2);
        for (int i = 0; i < count; i++) {
            long currentSeq = seq + i;
            String msgId = "mock-msg-" + currentSeq;
            messages.add(FinanceMessage.builder()
                    .seq(currentSeq)
                    .msgId(msgId)
                    .publicKeyVer(1)
                    .encryptRandomKey("mock-random-key-" + currentSeq)
                    .encryptChatMsg("mock-chat-msg-" + currentSeq)
                    .build());
        }
        return messages;
    }

    @Override
    public String decryptData(String encryptKey, String encryptChatMsg) {
        log.info("[MockFinanceSdk] decryptData encryptKey={}, msg={}", encryptKey, encryptChatMsg);
        try {
            // 模拟解密：直接返回一个结构化的 JSON 明文
            Map<String, Object> payload = Map.of(
                    "msgid", extractSeq(encryptChatMsg),
                    "action", "send",
                    "from", "MockUser",
                    "tolist", List.of("ExternalUser"),
                    "msgtype", "text",
                    "text", Map.of("content", "模拟会话存档消息：" + encryptChatMsg),
                    "msgtime", System.currentTimeMillis()
            );
            return OBJECT_MAPPER.writeValueAsString(payload);
        } catch (Exception e) {
            log.warn("[MockFinanceSdk] decryptData failed", e);
            return null;
        }
    }

    private String extractSeq(String encryptChatMsg) {
        if (encryptChatMsg == null) {
            return "mock-msg";
        }
        int idx = encryptChatMsg.lastIndexOf('-');
        return idx > 0 ? "mock-msg-" + encryptChatMsg.substring(idx + 1) : encryptChatMsg;
    }
}
