package tech.easyflow.chatlog.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tech.easyflow.chatlog.config.ChatSyncProperties;
import tech.easyflow.chatlog.service.ChatSyncService;
import tech.easyflow.common.cache.DistributedScheduledLock;

/**
 * 聊天记录同步定时任务。
 */
@Component
public class ChatSyncScheduler {

    private final ChatSyncService chatSyncService;
    private final ChatSyncProperties syncProperties;

    /**
     * 创建聊天记录同步定时任务。
     *
     * @param chatSyncService 聊天同步服务
     * @param syncProperties 同步配置
     */
    public ChatSyncScheduler(ChatSyncService chatSyncService, ChatSyncProperties syncProperties) {
        this.chatSyncService = chatSyncService;
        this.syncProperties = syncProperties;
    }

    /**
     * 同步聊天会话摘要。
     */
    @Scheduled(fixedDelayString = "${easyflow.chat.sync.fixed-delay:30000}", initialDelay = 10000L)
    @DistributedScheduledLock(key = "easyflow:schedule:chat-sync:sessions", leaseSeconds = 300L)
    public void syncSessions() {
        if (!syncProperties.isEnabled()) {
            return;
        }
        chatSyncService.syncSessions();
    }

    /**
     * 同步聊天日志明细。
     */
    @Scheduled(fixedDelayString = "${easyflow.chat.sync.fixed-delay:30000}", initialDelay = 15000L)
    @DistributedScheduledLock(key = "easyflow:schedule:chat-sync:logs", leaseSeconds = 300L)
    public void syncLogs() {
        if (!syncProperties.isEnabled()) {
            return;
        }
        chatSyncService.syncLogs();
    }

    /**
     * 修复近期聊天日志同步缺口。
     */
    @Scheduled(cron = "0 15 3 * * *")
    @DistributedScheduledLock(key = "easyflow:schedule:chat-sync:repair-logs", leaseSeconds = 300L)
    public void repairLogs() {
        if (!syncProperties.isEnabled()) {
            return;
        }
        chatSyncService.repairLogs();
    }

    /**
     * 维护聊天日志 MySQL 分表。
     */
    @Scheduled(cron = "0 0 2 * * *")
    @DistributedScheduledLock(key = "easyflow:schedule:chat-sync:maintain-mysql-tables", leaseSeconds = 300L)
    public void maintainMysqlTables() {
        chatSyncService.maintainMysqlTables();
    }
}
