package com.tashow.cloud.app.service.feishu;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 飞书卡片数据处理服务
 */
@Service
public class FeiShuCardDataService {

    private static final Logger log = LoggerFactory.getLogger(FeiShuCardDataService.class);
    private static final String REDIS_KEY_PREFIX = "feishu:card:";
    private static final int CARD_EXPIRATION_DAYS = 30;
    
    private final StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper objectMapper;

    @Autowired
    public FeiShuCardDataService(StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.objectMapper = objectMapper;
    }

    /**
     * 保存卡片数据到Redis
     */
    public boolean saveCardData(String messageId, Map<String, Object> data) {
        if (messageId == null || data == null) return false;
        
        try {
            String jsonData = objectMapper.writeValueAsString(data);
            stringRedisTemplate.opsForValue().set(
                REDIS_KEY_PREFIX + messageId, 
                jsonData, 
                CARD_EXPIRATION_DAYS, 
                TimeUnit.DAYS
            );
            return true;
        } catch (JsonProcessingException e) {
            log.error("保存卡片数据失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 从Redis获取卡片数据
     */
    public Map<String, Object> getCardData(String messageId) {
        try {
            String redisKey = REDIS_KEY_PREFIX + messageId;
            String jsonData = stringRedisTemplate.opsForValue().get(redisKey);
            
            if (jsonData == null) return new HashMap<>();
            
            @SuppressWarnings("unchecked")
            Map<String, Object> result = objectMapper.readValue(jsonData, Map.class);
            return result;
        } catch (Exception e) {
            log.error("获取卡片数据失败: {}", e.getMessage());
            return new HashMap<>();
        }
    }
} 