package com.mosquito.project.job;

import com.mosquito.project.domain.Activity;
import com.mosquito.project.domain.DailyActivityStats;
import com.mosquito.project.service.ActivityService;
import com.mosquito.project.persistence.entity.DailyActivityStatsEntity;
import com.mosquito.project.persistence.repository.DailyActivityStatsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class StatisticsAggregationJob {

    private static final Logger log = LoggerFactory.getLogger(StatisticsAggregationJob.class);

    private final ActivityService activityService;
    private final DailyActivityStatsRepository dailyStatsRepository;
    private final Map<Long, DailyActivityStats> dailyStats = new ConcurrentHashMap<>();

    public StatisticsAggregationJob(ActivityService activityService, DailyActivityStatsRepository dailyStatsRepository) {
        this.activityService = activityService;
        this.dailyStatsRepository = dailyStatsRepository;
    }

    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void aggregateDailyStats() {
        log.info("开始执行每日活动数据聚合任务");
        List<Activity> activities = activityService.getAllActivities();
        LocalDate yesterday = LocalDate.now().minusDays(1);

        for (Activity activity : activities) {
            // In a real application, you would query raw event data here.
            // For now, we simulate by calling the helper method.
            DailyActivityStats stats = aggregateStatsForActivity(activity, yesterday);
            // Upsert into persistence store for analytics queries
            upsertDailyStats(stats);
            log.info("为活动ID {} 聚合了数据: {} 次浏览, {} 次分享", activity.getId(), stats.getViews(), stats.getShares());
        }
        log.info("每日活动数据聚合任务执行完成");
    }

    // This is a helper method for simulation and testing
    public DailyActivityStats aggregateStatsForActivity(Activity activity, LocalDate date) {
        Random random = new Random();
        DailyActivityStats stats = new DailyActivityStats();
        stats.setActivityId(activity.getId());
        stats.setStatDate(date);
        stats.setViews(1000 + random.nextInt(500));
        stats.setShares(200 + random.nextInt(100));
        stats.setNewRegistrations(50 + random.nextInt(50));
        stats.setConversions(10 + random.nextInt(20));
        dailyStats.put(activity.getId(), stats);
        // Persist
        upsertDailyStats(stats);
        return stats;
    }

    private void upsertDailyStats(DailyActivityStats stats) {
        DailyActivityStatsEntity entity = dailyStatsRepository
            .findByActivityIdAndStatDate(stats.getActivityId(), stats.getStatDate())
            .orElseGet(DailyActivityStatsEntity::new);
        entity.setActivityId(stats.getActivityId());
        entity.setStatDate(stats.getStatDate());
        entity.setViews(stats.getViews());
        entity.setShares(stats.getShares());
        entity.setNewRegistrations(stats.getNewRegistrations());
        entity.setConversions(stats.getConversions());
        dailyStatsRepository.save(entity);
    }
}
