package com.dora.scheduler;

import com.dora.service.AdminToolConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * 工具使用统计定时任务
 * 每天凌晨1点统计前一天的数据
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ToolUsageStatsScheduler {

    private final AdminToolConfigService adminToolConfigService;

    /**
     * 每天凌晨1点执行，统计前一天的数据
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void refreshYesterdayStats() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        log.info("开始统计工具使用数据: date={}", yesterday);
        
        try {
            adminToolConfigService.refreshDailyStats(yesterday);
            log.info("工具使用统计完成: date={}", yesterday);
        } catch (Exception e) {
            log.error("工具使用统计失败: date={}", yesterday, e);
        }
    }

    /**
     * 每小时执行一次，更新当天的实时统计
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void refreshTodayStats() {
        LocalDate today = LocalDate.now();
        log.debug("更新今日工具使用统计: date={}", today);
        
        try {
            adminToolConfigService.refreshDailyStats(today);
        } catch (Exception e) {
            log.error("更新今日统计失败: date={}", today, e);
        }
    }
}
