package com.gxwebsoft.glt.task;

import com.gxwebsoft.common.core.annotation.IgnoreTenant;
import com.gxwebsoft.glt.service.GltUserTicketAutoReleaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 冻结水票自动释放任务：
 * - 扫描 glt_user_ticket_release 中到期且待释放（status=0）的记录
 * - 释放成功：frozen -> available，并将 release.status 置为 1
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "glt.ticket.auto-release", name = "enabled", havingValue = "true", matchIfMissing = true)
public class GltUserTicketAutoReleaseTask {

    private final GltUserTicketAutoReleaseService autoReleaseService;

    @Value("${glt.ticket.auto-release.batch-size:200}")
    private int batchSize;

    private final AtomicBoolean running = new AtomicBoolean(false);

    @Scheduled(cron = "${glt.ticket.auto-release.cron:0 */10 * * * ?}")
    @IgnoreTenant("定时任务无登录态，需忽略租户隔离；释放记录自带 tenantId，更新时会校验 tenantId")
    public void run() {
        if (!running.compareAndSet(false, true)) {
            log.warn("冻结水票自动释放任务仍在执行中，本轮跳过");
            return;
        }

        try {
            LocalDateTime now = LocalDateTime.now();
            int released = autoReleaseService.releaseDue(now, Math.max(batchSize, 1));
            if (released > 0) {
                log.info("冻结水票自动释放完成 - released={}, now={}", released, now);
            }
        } finally {
            running.set(false);
        }
    }
}
