package com.infoepoch.pms.agent.domain.care.state;

import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.config.JsonUtils;
import com.infoepoch.pms.agent.domain.care.model.CareConversationState;
import com.infoepoch.pms.agent.properties.CareAgentProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Optional;

/**
 * 会话状态缓存
 */
@Service
@RequiredArgsConstructor
public class CareConversationStateService {

    private static final String CARE_STATE_KEY_PREFIX = "care:state:";

    private final RedisTemplate<String, Object> redisTemplate;
    private final CareAgentProperties properties;

    /**
     * 按 sessionId 读取短会话状态。
     */
    public Optional<CareConversationState> load(String sessionId) {
        if (!StringUtils.hasText(sessionId)) {
            return Optional.empty();
        }
        Object cached = redisTemplate.opsForValue().get(buildKey(sessionId));
        if (cached == null) {
            return Optional.empty();
        }
        String cachedType = cached.getClass().getName();
        try {
            String json = JsonUtils.objectToJson(cached);
            if (!StringUtils.hasText(json)) {
                LogHelper.error(this, "读取会话状态转换失败，sessionId={}，cachedType={}，原因=对象转JSON为空", sessionId, cachedType);
                return Optional.empty();
            }
            CareConversationState state = JsonUtils.jsonToObject(json, CareConversationState.class);
            return Optional.ofNullable(state);
        } catch (RuntimeException exception) {
            LogHelper.error(
                    this,
                    "读取会话状态转换失败，sessionId={}，cachedType={}，异常={}",
                    sessionId,
                    cachedType,
                    exception.getMessage()
            );
            return Optional.empty();
        }
    }

    /**
     * 写入短会话状态并刷新 TTL。
     */
    public void save(CareConversationState state) {
        if (state == null || !StringUtils.hasText(state.sessionId())) {
            return;
        }
        redisTemplate.opsForValue().set(
                buildKey(state.sessionId()),
                state,
                Duration.ofMinutes(properties.getConversationTtlMinutes())
        );
    }

    /**
     * 生成 Redis key。
     */
    private String buildKey(String sessionId) {
        return CARE_STATE_KEY_PREFIX + sessionId;
    }
}
