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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.red.circle.other.infra.database.rds.dao.task.SpinsUserTaskProgressDAO;
import com.red.circle.other.infra.database.rds.entity.task.SpinsUserTaskProgress;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 重置任务进度执行器
 *
 * @author system
 * @date 2025-01-21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SpinsTaskProgressResetExe {

    private final SpinsUserTaskProgressDAO spinsUserTaskProgressDAO;

    /**
     * 执行重置用户每日任务
     *
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void execute(Long userId) {
        // 获取昨天的周期key
        String yesterdayCycleKey = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询昨天的每日任务进度
        List<SpinsUserTaskProgress> progressList = spinsUserTaskProgressDAO.selectList(
                new LambdaQueryWrapper<SpinsUserTaskProgress>()
                        .eq(SpinsUserTaskProgress::getUserId, userId)
                        .eq(SpinsUserTaskProgress::getCycleType, 1) // 每日任务
                        .eq(SpinsUserTaskProgress::getCycleKey, yesterdayCycleKey)
        );

        if (progressList.isEmpty()) {
            log.info("没有需要重置的每日任务, userId={}", userId);
            return;
        }

        log.info("重置用户每日任务成功, userId={}, 重置任务数={}", userId, progressList.size());
    }
}
