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

import cn.reghao.bnt.common.msg.event.EvtAppStatResult;
import cn.reghao.bnt.web.devops.aliyun.service.AliyunOss;
import cn.reghao.bnt.web.devops.app.model.po.AppBuilding;
import cn.reghao.bnt.web.devops.app.service.AppDeployService;
import cn.reghao.bnt.web.devops.builder.model.LocalBuildDir;
import cn.reghao.jutil.jdk.web.result.Result;
import lombok.extern.slf4j.Slf4j;

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

/**
 * OSS 部署前端静态文件任务
 *
 * @author reghao
 * @date 2025-06-05 10:26:31
 */
@Slf4j
public class OssDeployTask implements Runnable {
    private final AliyunOss aliyunOss;
    private final AppDeployService appDeployService;
    private final AppBuilding appBuilding;
    private final String machineId;

    public OssDeployTask(AliyunOss aliyunOss, AppDeployService appDeployService,
                         AppBuilding appBuilding, String machineId) {
        this.aliyunOss = aliyunOss;
        this.appDeployService = appDeployService;
        this.appBuilding = appBuilding;
        this.machineId = machineId;
    }

    @Override
    public void run() {
        String appId = appBuilding.getAppConfig().getAppId();
        String commitId = appBuilding.getCommitId();
        String dirname = String.format("%s_%s", appId, commitId);
        String destDirPath = LocalBuildDir.packDir + File.separator + appId + File.separator + dirname;
        File destDir = new File(destDirPath);
        if (destDir.exists()) {
            log.error("start oss deploy task with appId {}", appId);
            String bucketName = machineId.split("\\.")[1];
            // 匹配 bucket 下的所有文件
            String prefix = "";
            // 删除 bucket 下的所有文件
            aliyunOss.deleteObjects(bucketName, prefix);
            List<String> failedList = aliyunOss.uploadDir(bucketName, destDirPath);

            EvtAppStatResult deployResult = new EvtAppStatResult(appId, machineId);
            deployResult.setCommitId(commitId);
            Result result = Result.success();
            if (!failedList.isEmpty()) {
                String errMsg = failedList.size() > 10 ? failedList.subList(0, 10).toString() : failedList.toString();
                result = Result.fail(errMsg);
                deployResult.setRunning(false);
                deployResult.setStartTime(LocalDateTime.MIN);
                deployResult.setPid(-1);
                deployResult.setDeploy(false);
            } else {
                deployResult.setRunning(true);
                deployResult.setStartTime(LocalDateTime.now());
                deployResult.setPid(10086);
                deployResult.setDeploy(true);
            }
            deployResult.setResult(result);
            appDeployService.updateAfterDeploy(deployResult);
        } else {
            log.error("{} not exist", destDirPath);
        }
    }
}
