package com.red.circle.order.app.command.pay.web;

import com.google.api.client.util.Lists;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.order.app.dto.clientobject.pay.PayCountryCO;
import com.red.circle.order.infra.database.rds.entity.pay.PayCountry;
import com.red.circle.order.infra.database.rds.service.pay.PayCountryService;
import com.red.circle.other.inner.endpoint.sys.SysCountryCodeClient;
import com.red.circle.other.inner.model.dto.sys.SysCountryCodeDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 支付开通国家.
 *
 * @author pengliang on 2021/12/8
 */
@Component
@RequiredArgsConstructor
public class PayWebOpenPayCountryQueryExe {

  private final PayCountryService payCountryService;
  private final SysCountryCodeClient sysCountryCodeClient;
  private final PayCountryAliasResolver payCountryAliasResolver;

  public List<PayCountryCO> execute() {
    List<PayCountry> payCountries = payCountryService.listAllShelf();
    if (CollectionUtils.isEmpty(payCountries)) {
      return Lists.newArrayList();
    }
    Map<Long, SysCountryCodeDTO> countryCodeMap = ResponseAssert.requiredSuccess(
        sysCountryCodeClient
            .mapByIdes(
                payCountries.stream().map(PayCountry::getCountryId).collect(Collectors.toSet()))
    );
    return payCountries.stream().map(payCountry -> {
      PayCountry compatiblePayCountry = payCountryAliasResolver
          .resolveUsablePayCountryByCountryId(payCountry.getCountryId());
      if (compatiblePayCountry == null) {
        compatiblePayCountry = payCountry;
      }
      return new PayCountryCO()
          .setId(payCountry.getId())
          .setPayCountryId(compatiblePayCountry.getId())
          .setCountryId(payCountry.getCountryId())
          .setCurrency(compatiblePayCountry.getCurrency())
          .setCountry(countryCodeMap.get(payCountry.getCountryId()));
    }).collect(Collectors.toList());
  }
}
