package com.dora.config;

import com.dora.service.UvStatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * UV统计配置类
 * 配置定时任务和相关策略
 * 
 * @author dora
 * @date 2024/12/01
 */
@Slf4j
@Configuration
@EnableScheduling
@RequiredArgsConstructor
public class UvStatisticsConfig {

    private final UvStatisticsService uvStatisticsService;

    /**
     * 定时清理过期UV数据
     * 每天凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanExpiredUvData() {
        try {
            log.info("开始执行定时清理过期UV数据任务");
            uvStatisticsService.cleanExpiredUvData();
            log.info("定时清理过期UV数据任务完成");
        } catch (Exception e) {
            log.error("定时清理过期UV数据任务失败", e);
        }
    }

    /**
     * 定时统计UV数据
     * 每小时执行一次，用于数据校验和统计
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void hourlyUvStatistics() {
        try {
            log.debug("执行每小时UV数据统计检查");
            // 这里可以添加数据校验、异常检测等逻辑
            var todayUv = uvStatisticsService.getTodayUv();
            log.debug("当前UV统计 - UV: {}, PV: {}", todayUv.getUv(), todayUv.getPv());
        } catch (Exception e) {
            log.error("每小时UV统计检查失败", e);
        }
    }
}
