package cn.reghao.bnt.web.devops.build.service.impl;

import cn.reghao.bnt.web.devops.app.db.query.AppBuildQuery;
import cn.reghao.bnt.web.devops.build.db.repository.RepoAuthConfigRepository;
import cn.reghao.bnt.web.devops.build.model.po.RepoAuthConfig;
import cn.reghao.bnt.web.devops.build.service.RepoAuthConfigService;
import cn.reghao.bnt.web.devops.builder.chain.BuildTools;
import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.jdk.web.result.ResultStatus;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2021-09-17 10:16:07
 */
@Service
public class RepoAuthConfigServiceImpl implements RepoAuthConfigService {
    private final RepoAuthConfigRepository repoAuthConfigRepository;
    private final AppBuildQuery appBuildQuery;

    public RepoAuthConfigServiceImpl(RepoAuthConfigRepository repoAuthConfigRepository, AppBuildQuery appBuildQuery) {
        this.repoAuthConfigRepository = repoAuthConfigRepository;
        this.appBuildQuery = appBuildQuery;
    }

    @Override
    public Result addOrUpdate(RepoAuthConfig repoAuthConfig) {
        String name = repoAuthConfig.getName();
        RepoAuthConfig entity = repoAuthConfigRepository.findByName(name);
        if (entity == null) {
            repoAuthConfigRepository.save(repoAuthConfig);
            return Result.result(ResultStatus.SUCCESS);
        }

        repoAuthConfig.setEntity(entity);
        Result result = checkBeforeUpdate(repoAuthConfig);
        if (result.getCode() == ResultStatus.SUCCESS.getCode()) {
            repoAuthConfigRepository.save(repoAuthConfig);
        }

        return result;
    }

    /**
     * 检查是否有 AppConfig 正在使用
     *
     * @param
     * @return
     * @date 2023-03-12 18:41:55
     */
    private Result checkBeforeUpdate(RepoAuthConfig repoAuthConfig) {
        BuildTools.removeCodeUpdater(repoAuthConfig.getName());
        return Result.result(ResultStatus.SUCCESS);
    }

    @Override
    public Result delete(int id) {
        RepoAuthConfig repoAuthConfig = repoAuthConfigRepository.findById(id).orElse(null);
        if (repoAuthConfig != null) {
            BuildTools.removeCodeUpdater(repoAuthConfig.getName());
            repoAuthConfigRepository.deleteById(id);
        }

        return Result.result(ResultStatus.SUCCESS);
    }
}
