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

import com.red.circle.common.business.dto.cmd.app.AppUserIdCmd;
import com.red.circle.other.domain.enums.ContactMode;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.sys.CustomerServiceConfig;
import com.red.circle.other.infra.database.mongo.service.sys.CustomerServiceConfigService;
import com.red.circle.other.infra.database.mongo.service.user.profile.UserVipAbilitySettingService;
import com.red.circle.other.infra.database.rds.service.sys.AdministratorService;
import com.red.circle.other.infra.database.rds.service.user.user.RelationshipFriendService;

import java.util.List;
import java.util.Objects;
import java.util.Set;

import com.red.circle.other.inner.enums.material.SysNobleVipTypeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 检测是否是好友关系.
 *
 * @author pengliang on 2021/5/7
 */
@Component
@RequiredArgsConstructor
public class FriendCheckQryExe {

  private final AdministratorService administratorService;
  private final RelationshipFriendService relationshipFriendService;
  private final CustomerServiceConfigService customerServiceConfigService;
  private final UserVipAbilitySettingService userVipAbilitySettingService;
  private final UserProfileGateway userProfileGateway;

  public Boolean execute(AppUserIdCmd cmd) {
    Long reqUserId = cmd.requiredReqUserId();
    Long targetUserId = cmd.getUserId();

    // 1. 管理员优先
    Boolean isAdmin = administratorService.existsAvailable(
        Set.of(cmd.requiredReqUserId(), cmd.getUserId()));

    if (Objects.equals(isAdmin, Boolean.TRUE)) {
      return Boolean.TRUE;
    }

    // 2. 客服配置优先
    List<CustomerServiceConfig> configList = customerServiceConfigService.list(cmd.getReqSysOrigin().getOrigin(), "");
    boolean match = configList.stream().anyMatch(c -> c.getUserId().equals(cmd.getUserId()) || c.getUserId().equals(cmd.getReqUserId()));
    if (match) {
      return Boolean.TRUE;
    }

    // 3. 取目标用户的 ContactMode，结合其 VIP 等级修正后取实际生效的配置
    ContactMode rawContactMode = userVipAbilitySettingService.getContactMode(targetUserId);
    String targetVipName = userProfileGateway.getUserVipName(targetUserId);
    SysNobleVipTypeEnum targetVipEnum = SysNobleVipTypeEnum.getByName(targetVipName);
    ContactMode contactMode = resolveContactMode(rawContactMode, targetVipEnum);

    // 4. 拒绝联系
    if (ContactMode.DO_NOT_DISTURB.equals(contactMode)) {
      boolean isFriend = relationshipFriendService.checkFriend(reqUserId, targetUserId);
      if (!isFriend) {
        return Boolean.FALSE;
      }
      return Boolean.TRUE;
    }

    // 5. VIP2_ABOVE / VIP5_ABOVE → 检查发起方（reqUserId）的VIP等级是否足够
    if (contactMode.getMinTargetVipLevel() != null) {
      String reqVipName = userProfileGateway.getUserVipName(reqUserId);
      SysNobleVipTypeEnum reqVip = SysNobleVipTypeEnum.getByName(reqVipName);
      if (reqVip != null && reqVip.ordinal() >= contactMode.getMinTargetVipLevel().ordinal()) {
        return Boolean.TRUE;
      }
    }

    return relationshipFriendService
        .checkFriend(cmd.requiredReqUserId(), cmd.getUserId());
  }

  private ContactMode resolveContactMode(ContactMode mode, SysNobleVipTypeEnum vipEnum) {
    if (mode == null || mode == ContactMode.EVERYONE) {
      return ContactMode.EVERYONE;
    }
    if (mode == ContactMode.DO_NOT_DISTURB) {
      return (vipEnum != null && vipEnum.ordinal() >= SysNobleVipTypeEnum.DUKE.ordinal())
              ? mode : ContactMode.EVERYONE;
    }
    if (mode.getMinTargetVipLevel() != null) {
      return (vipEnum != null && vipEnum.ordinal() >= mode.getMinTargetVipLevel().ordinal())
              ? mode : ContactMode.EVERYONE;
    }
    return mode;
  }

}
