package com.xunhong.erp.turbo.user.app.executor.cmd;

import cn.hutool.crypto.digest.BCrypt;
import com.xunhong.erp.turbo.api.user.dto.cmd.UpdatePasswordCmd;
import com.xunhong.erp.turbo.api.user.dto.qry.UserAuthShowQry;
import com.xunhong.erp.turbo.api.user.exception.UserErrorCode;
import com.xunhong.erp.turbo.api.user.exception.UserException;
import com.xunhong.erp.turbo.user.domain.entity.UserAuth;
import com.xunhong.erp.turbo.user.domain.gateway.UserAuthGateway;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class UpdatePasswordCmdExe {
	private final UserAuthGateway userAuthGateway;

	public void execute(UpdatePasswordCmd updatePasswordCmd) {
		// 获取当前用户
		UserAuthShowQry userAuthShowQry = new UserAuthShowQry();
		userAuthShowQry.setUserId(updatePasswordCmd.getUserId());
		UserAuth userAuth = userAuthGateway.show(userAuthShowQry);

		// 判断旧密码是否正确
		if (!BCrypt.checkpw(updatePasswordCmd.getOldPassword(), userAuth.getPassword())) {
			throw new UserException("旧密码不正确", UserErrorCode.B_USER_USER_AUTH_PASSWORD_ERROR);
		}

		if (BCrypt.checkpw(updatePasswordCmd.getPassword(), userAuth.getPassword())) {
			throw new UserException("新密码不能与旧密码相同", UserErrorCode.B_USER_USER_AUTH_PASSWORD_ERROR);
		}

		// 判断两个密码是否一致
		if (!updatePasswordCmd.getPassword().equals(updatePasswordCmd.getConfirmPassword())) {
			throw new UserException("两次输入的密码", UserErrorCode.B_USER_USER_AUTH_PASSWORD_ERROR);
		}

		userAuthGateway.restPassword(updatePasswordCmd);
	}
}
