package com.yolo.keyboard.job;

import cn.hutool.core.collection.CollUtil;
import com.yolo.keyboard.dal.dataobject.user.KeyboardUserDO;
import com.yolo.keyboard.dal.mysql.user.KeyboardUserMapper;
import com.yolo.keyboard.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.yolo.keyboard.framework.quartz.core.handler.JobHandler;
import com.yolo.keyboard.framework.tenant.core.aop.TenantIgnore;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * VIP 到期检查定时任务
 * 定期执行，将 VIP 已过期的用户关闭 VIP 权限
 *
 * @author ziin
 */
@Component
@Slf4j
public class VipExpiryCheckJob implements JobHandler {

    @Resource
    private KeyboardUserMapper userMapper;

    @Override
    @TenantIgnore
    public String execute(String param) {
        log.info("[VipExpiryCheckJob] 开始执行 VIP 到期检查任务");

        LocalDateTime now = LocalDateTime.now();

        // 查询 VIP 已过期且仍处于 VIP 状态的用户
        List<KeyboardUserDO> expiredUsers = userMapper.selectList(
                new LambdaQueryWrapperX<KeyboardUserDO>()
                        .eq(KeyboardUserDO::getIsVip, true)
                        .le(KeyboardUserDO::getVipExpiry, now)
        );

        if (CollUtil.isEmpty(expiredUsers)) {
            log.info("[VipExpiryCheckJob] 没有需要处理的过期 VIP 用户");
            return "没有需要处理的过期 VIP 用户";
        }

        int count = 0;
        for (KeyboardUserDO user : expiredUsers) {
            user.setIsVip(false);
            user.setUpdatedAt(now);
            userMapper.updateById(user);
            count++;

            log.info("[VipExpiryCheckJob] 用户 {} VIP 已过期，已关闭 VIP 权限，过期时间: {}",
                    user.getUid(), user.getVipExpiry());
        }

        String result = String.format("共处理 %d 个过期 VIP 用户", count);
        log.info("[VipExpiryCheckJob] 任务执行完成: {}", result);
        return result;
    }
}
