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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.other.app.dto.cmd.user.relation.friend.FriendsApplyCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.user.friend.FriendApplyStatus;
import com.red.circle.other.infra.database.mongo.entity.user.friend.FriendsApply;
import com.red.circle.other.infra.database.mongo.service.user.friend.FriendsApplyListService;
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/5/6
 */
@Component
@RequiredArgsConstructor
public class UserSendFriendApplyCmdExe {

  // private final NativePushManager nativePushManager;
  private final UserProfileGateway userProfileGateway;
  private final FriendsApplyListService friendsApplyListService;

  public void execute(FriendsApplyCmd cmd) {
    ResponseAssert.isTrue(UserErrorCode.NOT_OPERATION_ME,
        !Objects.equals(cmd.requiredReqUserId(), cmd.getUserId()));

    // 无法操作，错误归属
    ResponseAssert.isTrue(CommonErrorCode.INOPERABLE_WRONG_ATTRIBUTION,
        StringUtils
            .startsWith(userProfileGateway.getSysOrigin(cmd.getUserId()),
                cmd.requireReqSysOrigin()));

    addApply(cmd);
    // sendPush(cmd);
  }

  private void addApply(FriendsApplyCmd cmd) {
    friendsApplyListService.add(new FriendsApply()
        .setTimingId(IdWorkerUtils.getId())
        .setApplyUserId(cmd.requiredReqUserId())
        .setUserId(cmd.getUserId())
        .setApplyDesc(cmd.getApplyDesc())
        .setStatus(FriendApplyStatus.FRIEND_APPLY)
        .setExpiredTime(TimestampUtils.nowPlusDays(7))
        .setCreateTime(TimestampUtils.now())
    );
  }

//  private void sendPush(FriendsApplyCmd cmd) {
//    nativePushManager.oneToOneUnicastAsync(OneToOnePushNativeParam.builder()
//        .acceptUserId(cmd.getUserId())
//        .event(NativeEventEnum.FRIEND_APPLY)
//        .pushParam(OneToOnePushNativeParam.createPushParam(cmd.getSysOrigin(),
//            NativeEventEnum.FRIEND_APPLY.getI18nTitle(),
//            NativeEventEnum.FRIEND_APPLY.getI18nBodyFormat(MapBuilder.builder()
//                .put("nickname",
//                    cacheUserProfileManagerService.getUserNickname(cmd.getCmdOriginUserId()))
//                .put("content", cmd.getApplyDesc())
//                .build())))
//        .build());
//  }
}
