package cn.reghao.bnt.web.devops.app.task;

import cn.reghao.bnt.web.devops.aliyun.model.vo.RefreshStatus;
import cn.reghao.bnt.web.devops.aliyun.service.AliyunCdn;
import cn.reghao.bnt.web.devops.app.model.vo.msg.CdnRereshNotifyMsg;
import cn.reghao.bnt.web.devops.app.service.bd.BuildDeployNotify;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @author reghao
 * @date 2025-07-31 16:58:28
 */
@Slf4j
public class RereshCheckTask implements Runnable {
    private final AliyunCdn aliyunCdn;
    private final BuildDeployNotify buildDeployNotify;
    private final String taskId;
    private final String buildId;
    private final String appId;
    private final String domain;

    public RereshCheckTask(AliyunCdn aliyunCdn, BuildDeployNotify buildDeployNotify, String taskId,
                           String buildId, String appId, String domain) {
        this.aliyunCdn = aliyunCdn;
        this.buildDeployNotify = buildDeployNotify;
        this.taskId = taskId;
        this.buildId = buildId;
        this.appId = appId;
        this.domain = domain;
    }

    @Override
    public void run() {
        try {
            RefreshStatus refreshStatus = aliyunCdn.getRefreshStatus(taskId);
            if (refreshStatus == null) {
                Thread.sleep(10_000);
                refreshStatus = aliyunCdn.getRefreshStatus(taskId);
                if (refreshStatus == null) {
                    log.error("can't get RefreshStatus with task id -> {}", taskId);
                    return;
                }
            }

            int count = 1;
            while (!refreshStatus.getStatus().equals("Complete") && count < 10) {
                Thread.sleep(6_000);
                refreshStatus = aliyunCdn.getRefreshStatus(taskId);
                count++;
            }

            LocalDateTime refreshTime = refreshStatus.getStartAt();
            String result = "";
            if (refreshStatus.getStatus().equals("Complete")) {
                result = "CDN 刷新完成";
            } else {
                result = String.format("等待 60s 后 CDN 尚未刷新完成, 当前进度 %s", refreshStatus.getProcess());
            }

            CdnRereshNotifyMsg cdnRereshNotifyMsg = new CdnRereshNotifyMsg(buildId, appId, domain, refreshTime, result);
            buildDeployNotify.refreshNotify(cdnRereshNotifyMsg);
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
    }
}
