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.app.convertor.team.TeamAppConvertor;
import com.red.circle.other.app.dto.clientobject.team.TeamPolicyManagerCO;
import com.red.circle.other.app.service.user.user.UserProfileService;
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.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.inner.asserts.team.TeamErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Map;
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;

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

    UserProfile userProfile = userProfileGateway.getByUserId(teamProfile.getOwnUserId());

    Map<String, TeamPolicyManager> policyManagerMap = teamPolicyManagerService.mapRegionReleaseWithCountry(Set.of(teamProfile.getRegion()));
    TeamPolicyManager teamPolicyManager = TeamBillCycleUtils.getPolicyFromMap(policyManagerMap, teamProfile.getRegion(), userProfile.getCountryCode());

    return teamAppConvertor.toTeamPolicyManagerCO(teamPolicyManager);
  }

}
