package tech.easyflow.chatlog.service.impl;

import org.springframework.stereotype.Service;
import tech.easyflow.chatlog.cache.ChatHotStateService;
import tech.easyflow.chatlog.domain.dto.ChatMessageRecord;
import tech.easyflow.chatlog.domain.dto.ChatRoundRecord;
import tech.easyflow.chatlog.repository.mysql.MySqlChatLogRepository;
import tech.easyflow.chatlog.repository.mysql.MySqlChatLogTableManager;
import tech.easyflow.chatlog.repository.mysql.MySqlChatRoundRepository;
import tech.easyflow.chatlog.service.ChatRoundQueryService;

import java.math.BigInteger;
import java.util.List;

/**
 * 聊天轮次读服务实现。
 */
@Service
public class ChatRoundQueryServiceImpl implements ChatRoundQueryService {

    private final MySqlChatRoundRepository roundRepository;
    private final MySqlChatLogRepository logRepository;
    private final MySqlChatLogTableManager tableManager;
    private final ChatHotStateService chatHotStateService;

    public ChatRoundQueryServiceImpl(MySqlChatRoundRepository roundRepository,
                                     MySqlChatLogRepository logRepository,
                                     MySqlChatLogTableManager tableManager,
                                     ChatHotStateService chatHotStateService) {
        this.roundRepository = roundRepository;
        this.logRepository = logRepository;
        this.tableManager = tableManager;
        this.chatHotStateService = chatHotStateService;
    }

    @Override
    public ChatRoundRecord getLatestRound(BigInteger sessionId) {
        ChatRoundRecord cached = chatHotStateService.getLatestRound(sessionId);
        if (cached != null) {
            return cached;
        }
        ChatRoundRecord record = roundRepository.findLatestRound(sessionId);
        if (record != null) {
            chatHotStateService.cacheRound(record);
        }
        return record;
    }

    @Override
    public ChatRoundRecord getRound(BigInteger sessionId, BigInteger roundId) {
        ChatRoundRecord cached = chatHotStateService.getRound(sessionId, roundId);
        if (cached != null) {
            return cached;
        }
        ChatRoundRecord record = roundRepository.findRound(sessionId, roundId);
        if (record != null) {
            chatHotStateService.cacheRound(record);
        }
        return record;
    }

    @Override
    public List<ChatMessageRecord> listRoundVariants(BigInteger sessionId, BigInteger roundId) {
        return logRepository.listRoundVariants(sessionId, roundId, tableManager.listRecentExistingMonths(3));
    }

    @Override
    public ChatMessageRecord getRoundVariant(BigInteger sessionId, BigInteger roundId, Integer variantIndex) {
        return logRepository.findRoundVariant(sessionId, roundId, variantIndex, tableManager.listRecentExistingMonths(3));
    }

    @Override
    public boolean hasRounds(BigInteger sessionId) {
        return roundRepository.existsRounds(sessionId);
    }
}
