package com.moka.gdtauto.task;

import com.moka.gdtauto.entity.TencentAdsAuth;
import com.moka.gdtauto.service.TencentAdsAuthService;
import com.tencent.ads.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 腾讯广告Token维护定时任务
 * 自动刷新即将过期的访问令牌
 * 
 * @author moka
 * @since 2026-02-03
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenRefreshTask {

    private final TencentAdsAuthService authService;

    /**
     * 刷新即将过期的访问令牌
     * 每10分钟执行一次，刷新30分钟内即将过期的token
     */
    @Scheduled(cron = "0 */10 * * * ?")
    @SchedulerLock(name = "refreshExpiringTokens", lockAtMostFor = "9m", lockAtLeastFor = "1m")
    public void refreshExpiringTokens() {
        log.info("开始执行Token刷新定时任务");
        
        try {
            // 获取即将过期的授权信息（30分钟内过期）
            List<TencentAdsAuth> expiringAuths = authService.listExpiringAuths();
            
            if (expiringAuths.isEmpty()) {
                log.info("没有需要刷新的Token");
                return;
            }
            
            log.info("找到 {} 个即将过期的Token，开始刷新", expiringAuths.size());
            
            int successCount = 0;
            int failCount = 0;
            
            // 逐个刷新
            for (TencentAdsAuth auth : expiringAuths) {
                try {
                    authService.refreshAccessToken(auth);
                    successCount++;
                    log.info("账户 {} 的Token刷新成功", auth.getAccountId());
                } catch (ApiException e) {
                    failCount++;
                    log.error("账户 {} 的Token刷新失败：{}", auth.getAccountId(), e.getMessage());
                }
            }
            
            log.info("Token刷新任务完成，成功：{}，失败：{}", successCount, failCount);
            
        } catch (Exception e) {
            log.error("Token刷新任务执行异常", e);
        }
    }
}
