// 路径: rc-service-other/other-application/src/main/java/com/red/circle/other/app/scheduler/RocketStatusSyncTask.java

package com.red.circle.other.app.scheduler;

import cn.hutool.core.date.DateUtil;
import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.other.app.service.room.RocketStatusCacheService;
import com.red.circle.other.domain.gateway.RocketStatusGateway;
import com.red.circle.other.domain.rocket.RocketStatus;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 火箭状态同步定时任务
 * 每5分钟同步一次所有房间的火箭状态到缓存
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RocketStatusSyncTask {

    private final RocketStatusGateway rocketStatusGateway;
    private final RocketStatusCacheService rocketStatusCacheService;

    /**
     * 每5分钟同步一次火箭状态
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @TaskCacheLock(key = "ROCKET_STATUS_SYNC_TASK", expireSecond = 60 * 4)
    public void syncRocketStatus() {
        try {
            // 获取当前日期 格式: yyyyMMdd
            String riyadhToday = ZonedDateTimeAsiaRiyadhUtils.nowFormat("yyyy-MM-dd");

            // 查询今天所有房间的火箭状态
            List<RocketStatus> rocketStatusList = rocketStatusGateway.listByDate(riyadhToday);

            if (CollectionUtils.isEmpty(rocketStatusList)) {
                log.info("火箭状态同步完成，当前无活跃火箭");
                return;
            }

            // 批量更新缓存
            rocketStatusCacheService.batchSetRocketStatus(rocketStatusList);

            log.info("火箭状态同步完成，同步数量: {}", rocketStatusList.size());
        } catch (Exception e) {
            log.error("火箭状态同步失败", e);
        }
    }
}