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

import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.cmd.team.DbLeaderInviteBdCmd;
import com.red.circle.other.app.util.OfficialNoticeUtils;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.infra.database.mongo.entity.team.bd.BdInviteAgentMessage;
import com.red.circle.other.infra.database.mongo.entity.team.bd.MessageInviteGroup;
import com.red.circle.other.infra.database.mongo.service.team.bd.BdInviteAgentMessageService;
import com.red.circle.other.infra.database.rds.service.sys.AdministratorService;
import com.red.circle.other.infra.database.rds.service.team.AdminRechargeAgentRelationService;
import com.red.circle.other.inner.asserts.team.TeamErrorCode;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.wallet.inner.endpoint.freight.FreightGoldClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 管理员邀请充值代理.
 *
 * @author tf
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminInviteRechargeAgentExe {

  private final AdministratorService administratorService;
  private final UserProfileGateway userProfileGateway;
  private final OfficialNoticeClient officialNoticeClient;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final BdInviteAgentMessageService bdInviteAgentMessageService;
  private final AdminRechargeAgentRelationService adminRechargeAgentRelationService;
  private final FreightGoldClient freightGoldClient;
  private final UserRegionGateway userRegionGateway;

  public void execute(DbLeaderInviteBdCmd cmd) {

    // 权限验证：必须是管理员
    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        administratorService.existsAdmin(cmd.requiredReqUserId()));

    // 被邀请用户必须是充值代理
    ResponseAssert.isTrue(TeamErrorCode.USER_IS_NOT_RECHARGE_AGENT,
        ResponseAssert.requiredSuccess(freightGoldClient.checkFreightAgent(cmd.getInviteUserId())));

    // 该用户已经被邀请过了
    ResponseAssert.isFalse(TeamErrorCode.USER_IS_ALREADY_A_RECHARGE_AGENT,
        adminRechargeAgentRelationService.checkRechargeAgent(cmd.getInviteUserId()));

    // 验证区域是否一致
    Boolean eqRegion = userRegionGateway.checkEqRegion(cmd.requiredReqUserId(),
        cmd.getInviteUserId());
    ResponseAssert.isTrue(TeamErrorCode.NOT_INVITE_USER_ERROR, eqRegion);

    // 消息已发送
    ResponseAssert.isFalse(TeamErrorCode.MESSAGE_PROCESSED,
        bdInviteAgentMessageService.existsWaitMessage(cmd.requiredReqUserId(),
            cmd.getInviteUserId(), MessageInviteGroup.ADMIN_INVITE_RECHARGE_AGENT.name()));

    String messageId = IdWorkerUtils.getIdStr();
    bdInviteAgentMessageService.add(new BdInviteAgentMessage()
        .setId(messageId)
        .setSysOrigin(cmd.requireReqSysOrigin())
        .setUserId(cmd.requiredReqUserId())
        .setInviteUserId(cmd.getInviteUserId())
        .setMessage(cmd.getMessage())
        .setGroup(MessageInviteGroup.ADMIN_INVITE_RECHARGE_AGENT.name())
        .setCreateTime(TimestampUtils.now())
        .setUpdateTime(TimestampUtils.now())
        .setStatus(0)
        .setExpiredTime(TimestampUtils.nowPlusDays(2))
    );

    UserProfileDTO userProfile = userProfileAppConvertor.toUserProfileDTO(
        userProfileGateway.getByUserId(cmd.requiredReqUserId())
    );

    officialNoticeClient.send(NoticeExtTemplateTypeCmd.builder()
        .toAccount(cmd.getInviteUserId())
        .noticeType(OfficialNoticeTypeEnum.ADMIN_INVITE_RECHARGE_AGENT)
        .templateParam(OfficialNoticeUtils.buildUserProfile(userProfile))
        .expand(messageId)
        .build()
    );

  }

}
