package com.red.circle.other.app.command.user;

import com.red.circle.external.inner.endpoint.message.SmsClient;
import com.red.circle.external.inner.model.cmd.message.SendSmsCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.cmd.user.account.ForgetPwdResetCmd;
import com.red.circle.other.infra.database.rds.entity.user.user.MobileAuth;
import com.red.circle.other.infra.database.rds.service.user.device.ArchiveDeviceService;
import com.red.circle.other.infra.database.rds.service.user.user.MobileAuthService;
import com.red.circle.other.inner.asserts.user.UserErrorCode;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 忘记密码重置.
 *
 * @author pengliang on 2021/3/25
 */
@Component
@RequiredArgsConstructor
public class ForgetPwdResetCmdExe {

  private final SmsClient smsClient;
  private final MobileAuthService mobileAuthService;
  private final ArchiveDeviceService archiveDeviceService;

  public void execute(ForgetPwdResetCmd cmd) {

    // 设备不可用
    ResponseAssert.isFalse(CommonErrorCode.DEVICE_UNAVAILABLE,
        archiveDeviceService.existsDevice(cmd.getReqImei(), cmd.requireReqSysOrigin()));

    // 验证码不匹配
    ResponseAssert.requiredSuccess(smsClient.checkCode(new SendSmsCmd()
            .setPhonePrefix(cmd.getPhonePrefix())
            .setPhoneNumber(cmd.getPhoneNumber())
            .setCode(cmd.getCode())
        )
    );

    MobileAuth mobileAuth = mobileAuthService
        .getByPhone(cmd.getPhonePrefix(), cmd.getPhoneNumber());

    // 用户未注册
    ResponseAssert.notNull(UserErrorCode.USER_NOT_REGISTERED, mobileAuth);

    // 注册黑名单
    ResponseAssert.isFalse(UserErrorCode.REGISTER_BLACKLIST,
        Objects.equals(mobileAuth.getDel(), Boolean.TRUE));

    // 操作失败
    ResponseAssert.isTrue(CommonErrorCode.OPERATING_FAILURE,
        mobileAuthService.resetPassword(mobileAuth.getId(), cmd.getPwd()));

  }

}
