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

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.dto.cmd.user.user.UserSpecialIdApplyCmd;
import com.red.circle.other.domain.model.user.UserConsumptionLevel;
import com.red.circle.other.infra.database.mongo.service.user.profile.UserSpecialIdService;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.rds.entity.user.user.UserBeautifulNumberApply;
import com.red.circle.other.infra.database.rds.service.user.user.UserBeautifulNumberApplyService;
import com.red.circle.other.inner.asserts.user.UserSpecialErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户靓号申请 实现.
 *
 * @author pengshiang on 2021/8/18
 */
@Component
@RequiredArgsConstructor
public class UserBeautifulNumberApplyCmdExe {

  private final UserProfileGateway userProfileGateway;
  private final UserBeautifulNumberApplyService userBeautifulNumberApplyService;
  private final UserSpecialIdService userSpecialIdService;

  public void execute(UserSpecialIdApplyCmd cmd) {
    String account = cmd.getAccount();
    Long userId = cmd.getReqUserId();

    UserConsumptionLevel consumptionLevel = userProfileGateway.getUserConsumptionLevel(SysOriginPlatformEnum.LIKEI, userId);
    Integer wealthLevel = consumptionLevel.getWealthLevel();

    // (1) 财富等级>=10级校验
    ResponseAssert.isTrue(
        UserSpecialErrorCode.WEALTH_LEVEL_NOT_ENOUGH,
        wealthLevel != null && wealthLevel >= 10
    );

    // (2) ID格式校验：2-8位数字
    ResponseAssert.isTrue(
        UserSpecialErrorCode.ID_FORMAT_INVALID,
        account != null && account.matches("^\\d{2,8}$")
    );

    // (3) 用户在当前财富等级已申请过ID（待审核）
    Boolean hasPendingApply = userBeautifulNumberApplyService.hasPendingApplyAtLevel(userId, wealthLevel);
    ResponseAssert.isFalse(
        UserSpecialErrorCode.APPLICATION_PENDING,
        Boolean.TRUE.equals(hasPendingApply)
    );

    // (4) 用户在当前财富等级已经申请过ID（申请成功）- 通过数据库判断
    Boolean hasAppliedFailed = userBeautifulNumberApplyService.hasAppliedAtLevelWithFailure(userId, wealthLevel);
    ResponseAssert.isFalse(
        UserSpecialErrorCode.ALREADY_APPLIED_AT_LEVEL,
        Boolean.TRUE.equals(hasAppliedFailed)
    );

    // (5) 检查靓号是否已被使用
    boolean exists = userSpecialIdService.exists(cmd.getReqSysOrigin().getOrigin(), account);
    ResponseAssert.isFalse(
        UserSpecialErrorCode.ID_ALREADY_USED,
        exists
    );

    // 保存申请记录
    userBeautifulNumberApplyService.save(new UserBeautifulNumberApply()
        .setId(IdWorkerUtils.getId())
        .setApplyUser(cmd.requiredReqUserId())
        .setApplyAccount(account)
        .setWealthLevel(wealthLevel)
        .setState(0)
        .setSysOrigin(cmd.requireReqSysOrigin())
    );
  }

}
