package cd.casic.module.terminal.host.config.strategy;

import cd.casic.module.machine.dal.mysql.MachineInfoMapper;
import cd.casic.module.machine.dal.mysql.SecretKeyMapper;
import cd.casic.module.terminal.common.AbstractGenericsDataStrategy;
import cd.casic.module.terminal.common.AesEncryptUtils;
import cd.casic.module.terminal.common.ErrorMessage;
import cd.casic.module.terminal.enums.HostSshAuthTypeEnum;
import cd.casic.module.terminal.host.config.model.HostSshConfigModel;
import cd.casic.module.terminal.utils.RsaParamDecryptUtils;
import cd.casic.module.terminal.utils.Valid;
import cn.orionsec.kit.lang.constant.Const;
import cn.orionsec.kit.lang.utils.Booleans;
import cn.orionsec.kit.lang.utils.Charsets;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 主机 SSH 配置策略
 *
 * @author Jiahang Li
 * @version 1.0.0
 * @since 2023/9/19 14:26
 */
@Component
public class HostSshConfigStrategy extends AbstractGenericsDataStrategy<HostSshConfigModel> {

    @Autowired
    private SecretKeyMapper secretKeyMapper;

    @Autowired
    private MachineInfoMapper machineInfoMapper;

    private static final String USERNAME = "root";

    public HostSshConfigStrategy() {
        super(HostSshConfigModel.class);
    }

    @Override
    public HostSshConfigModel getDefault() {
        return HostSshConfigModel.builder()
                .port(22)
                .username(USERNAME)
                .authType(HostSshAuthTypeEnum.PASSWORD.name())
                .connectTimeout(Const.MS_S_10)
                .charset(Const.UTF_8)
                .fileNameCharset(Const.UTF_8)
                .fileContentCharset(Const.UTF_8)
                .build();
    }

    @Override
    protected void preValid(HostSshConfigModel model) {
        // 验证编码格式
        this.validCharset(model.getCharset());
        this.validCharset(model.getFileNameCharset());
        this.validCharset(model.getFileContentCharset());
        // 检查主机密钥是否存在
        Long keyId = model.getKeyId();
        if (keyId != null) {
            Valid.notNull(secretKeyMapper.selectById(keyId), ErrorMessage.KEY_ABSENT);
        }
        // 检查主机身份是否存在
        Long identityId = model.getIdentityId();
        if (identityId != null) {
            Valid.notNull(machineInfoMapper.selectById(identityId), ErrorMessage.IDENTITY_ABSENT);
        }
    }

    @Override
    protected void valid(HostSshConfigModel model) {
        // 验证填充后的参数
        Valid.valid(model);
    }

    @Override
    protected void updateFill(HostSshConfigModel beforeModel, HostSshConfigModel afterModel) {
        // 加密密码
        this.checkEncryptPassword(beforeModel, afterModel);
        afterModel.setHasPassword(null);
        afterModel.setUseNewPassword(null);
    }

    @Override
    public void toView(HostSshConfigModel model) {
        if (model == null) {
            return;
        }
        model.setHasPassword(Strings.isNotBlank(model.getPassword()));
        model.setPassword(null);
    }

    /**
     * 检查加密密码
     *
     * @param before before
     * @param after  after
     */
    private void checkEncryptPassword(HostSshConfigModel before, HostSshConfigModel after) {
        // 非密码认证/使用原始密码则直接赋值
        if (!HostSshAuthTypeEnum.PASSWORD.name().equals(after.getAuthType())
                || !Booleans.isTrue(after.getUseNewPassword())) {
            if (before != null) {
                after.setPassword(before.getPassword());
            }
            return;
        }
        // 检查新密码
        String newPassword = Valid.notBlank(after.getPassword(), ErrorMessage.PASSWORD_MISSING);
        // 解密密码
        newPassword = RsaParamDecryptUtils.decrypt(newPassword);
        Valid.notBlank(newPassword, ErrorMessage.DECRYPT_ERROR);
        // 设置密码
        after.setPassword(AesEncryptUtils.encryptAsString(newPassword));
    }

    /**
     * 检查编码格式
     *
     * @param charset charset
     */
    private void validCharset(String charset) {
        Valid.isTrue(Charsets.isSupported(charset), ErrorMessage.UNSUPPORTED_CHARSET, charset);
    }

}
