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

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.infra.database.rds.entity.user.user.AccountAuth;
import com.red.circle.other.infra.database.rds.entity.user.user.PasswordLog;
import com.red.circle.other.infra.database.rds.service.user.user.AccountAuthService;
import com.red.circle.other.infra.database.rds.service.user.user.AuthTypeService;
import com.red.circle.other.infra.database.rds.service.user.user.PasswordLogService;
import com.red.circle.other.inner.asserts.user.UserErrorCode;
import com.red.circle.other.inner.model.cmd.user.account.AccountPwdResetCmd;
import com.red.circle.other.inner.enums.user.AuthTypeEnum;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 账号密码重置.
 *
 * @author zongpubin on 2023/9/13
 */
@Component
@AllArgsConstructor
public class AccountPwdResetCmdExe {

  private final RedisService redisService;
  private final AuthTypeService authTypeService;
  private final AccountAuthService accountAuthService;
  private final PasswordLogService passwordLogService;

  public void execute(AccountPwdResetCmd cmd) {

    String key = "UN_BIND_USER_ACCOUNT_AUTH_TYPE:" + cmd.getReqUserId();
    if (redisService.lock(key, 60)) {
      AccountAuth accountAuth = accountAuthService.getByPassword(cmd.getPwd(), cmd.getReqUserId());

      ResponseAssert.notNull(UserErrorCode.PASSWORD_NOT_MATCH_THREE, accountAuth);

      List<String> authTypes = authTypeService.listUserAuthType(cmd.getReqUserId());
      // 4051 最少保留一个
      ResponseAssert.isTrue(UserErrorCode.KEEP_AT_LEAST_ONE,
          CollectionUtils.isNotEmpty(authTypes) && authTypes.size() > 1);
      authTypeService.deleteAuthType(cmd.getReqUserId(), AuthTypeEnum.ACCOUNT.name());
      // 1036 操作失败
      ResponseAssert.isTrue(CommonErrorCode.OPERATING_FAILURE,
          accountAuthService.deleteById(accountAuth.getId()));

      passwordLogService.save(PasswordLog.builder()
          .businessType("ACCOUNT_PASSWORD")
          .operateType("UPDATE_PASSWORD")
          .userId(cmd.getReqUserId())
          .sysOrigin(cmd.requireReqSysOrigin())
          .pwd(cmd.getPwd())
          .imei(cmd.getReqImei())
          .build());
      redisService.unlock(key);
      return;
    }
    ResponseAssert.failure(CommonErrorCode.REQUEST_LIMITING);

  }

}
