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

import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.infra.common.sys.CountryCodeAliasSupport;
import com.red.circle.other.app.convertor.team.TeamAppConvertor;
import com.red.circle.other.app.dto.clientobject.team.TeamPolicyManagerCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamPolicyManager;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamProfile;
import com.red.circle.other.infra.database.mongo.entity.user.region.SysRegionConfig;
import com.red.circle.other.infra.database.mongo.service.team.TeamBillCycleUtils;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamPolicyManagerService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamProfileService;
import com.red.circle.other.infra.database.mongo.service.user.region.SysRegionConfigService;
import com.red.circle.other.inner.asserts.team.TeamErrorCode;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

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

/**
 * 团队最新发布政策.
 *
 * @author pengliang on 2022/12/26
 */
@Component
@RequiredArgsConstructor
public class TeamReleasePolicyQryExe {

  private final TeamAppConvertor teamAppConvertor;
  private final TeamProfileService teamProfileService;
  private final TeamPolicyManagerService teamPolicyManagerService;
  private final UserProfileGateway userProfileGateway;
  private final SysRegionConfigService sysRegionConfigService;
  private final CountryCodeAliasSupport countryCodeAliasSupport;

  public TeamPolicyManagerCO execute(AppIdLongCmd cmd) {
    TeamProfile teamProfile = teamProfileService.getById(cmd.getId());
    ResponseAssert.notNull(TeamErrorCode.TEAM_NOT_FOUND, teamProfile);

    UserProfile userProfile = userProfileGateway.getByUserId(teamProfile.getOwnUserId());
    String countryCode = Objects.nonNull(userProfile) ? userProfile.getCountryCode() : null;
    String policyRegion = resolveOwnerCountryRegion(teamProfile, countryCode);

    Map<String, TeamPolicyManager> policyManagerMap = teamPolicyManagerService.mapRegionReleaseWithCountry(Set.of(policyRegion));
    TeamPolicyManager teamPolicyManager = TeamBillCycleUtils.getPolicyFromMap(policyManagerMap, policyRegion, countryCode);

    return teamAppConvertor.toTeamPolicyManagerCO(teamPolicyManager);
  }

  private String resolveOwnerCountryRegion(TeamProfile teamProfile, String countryCode) {
    List<SysRegionConfig> regionConfigs = sysRegionConfigService.listAvailable(teamProfile.getSysOrigin());
    if (regionConfigs == null || regionConfigs.isEmpty()) {
      return teamProfile.getRegion();
    }

    if (StringUtils.isNotBlank(countryCode)) {
      SysRegionConfig countryRegion = regionConfigs.stream()
          .filter(region -> StringUtils.isNotBlank(region.getCountryCodes()))
          .filter(region -> countryCodeAliasSupport.containsCode(region.getCountryCodes(), countryCode))
          .findFirst()
          .orElse(null);
      if (Objects.nonNull(countryRegion)) {
        return countryRegion.getId();
      }
    }

    return regionConfigs.stream()
        .filter(region -> StringUtils.equalsIgnoreCase("OTHER", region.getRegionCode()))
        .findFirst()
        .map(SysRegionConfig::getId)
        .orElse(teamProfile.getRegion());
  }

}
