package com.red.circle.game.fruit.core.token;

import com.red.circle.framework.core.security.UserCredential;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 解析令牌.
 *
 * @author pengliang on 2023/12/22
 */
@Component
@RequiredArgsConstructor
public class AnalysisToken {

  @Value("${spring.profiles.active:undefined}")
  private String profileActive;
  private final AnalysisTokenDevApi analysisTokenDevApi;
  private final AnalysisTokenProdApi analysisTokenProdApi;
  private final AnalysisTokenLocalApi analysisTokenLocalApi;


  public String getUserId(String token) {
    if (StringUtils.isBlank(token)) {
      throw new IllegalArgumentException("token required.");
    }

    if (token.startsWith("sg.")) {
      return reqHistoryUserIdUrl(token);
    }

    UserCredential userCredential = UserCredential.parseToken(token);
    return Objects.toString(userCredential.getUserId());
  }

  private String reqHistoryUserIdUrl(String token) {
    if (checkProd()) {
      return analysisTokenProdApi.getUserId(token).getBody();
    }

    if (checkDev()) {
      return analysisTokenDevApi.getUserId(token).getBody();
    }

    return analysisTokenLocalApi.getUserId(token).getBody();
  }

  private boolean checkProd() {
    return Objects.equals(profileActive, "prod");
  }

  private boolean checkDev() {
    return Objects.equals(profileActive, "dev");
  }

}
