package com.red.circle.other.infra.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

/**
 * IP 归属国家查询工具.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IpCountryUtils {

  private static final String APPCODE = "APPCODE ****";
  private static final String REQUEST_URL = "https://c2ba.api.huachen.cn/ip";
  private static final String REDIS_KEY_PREFIX = "IP_COUNTRY:";

  private final RedisService redisService;

  /**
   * 根据 IP 获取国家二字码（如 US、CN、HK）.
   * 结果缓存到 Redis，永久有效（IP 归属地基本不变）.
   *
   * @param ip 用户 IP
   * @return 国家二字码，查询失败返回空字符串
   */
  public String getCountryCode(String ip) {
    if (StringUtils.isBlank(ip)) {
      return "";
    }
    String redisKey = REDIS_KEY_PREFIX + ip;
    String cached = redisService.getString(redisKey);
    if (StringUtils.isNotBlank(cached)) {
      return cached;
    }

    HttpGet httpGet = new HttpGet(REQUEST_URL + "?ip=" + ip);
    httpGet.addHeader("Authorization", APPCODE);
    RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(60000).setSocketTimeout(60000).setConnectionRequestTimeout(60000).build();

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
         CloseableHttpResponse response = httpClient.execute(httpGet)) {
      String result = EntityUtils.toString(response.getEntity());
      log.info("IpCountryUtils ip={} result={}", ip, result);
      JSONObject jsonObject = JSON.parseObject(result);
      if (Objects.equals(jsonObject.getInteger("ret"), 200)) {
        JSONObject data = jsonObject.getJSONObject("data");
        String countryId = data.getString("country_id");
        if (StringUtils.isNotBlank(countryId)) {
          redisService.setString(redisKey, countryId);
          return countryId;
        }
      }
    } catch (Exception e) {
      log.error("IpCountryUtils ip={} error={}", ip, e.getMessage());
    }
    return "";
  }

  /**
   * 判断 IP 是否属于美国.
   */
  public boolean isUsIp(String ip) {
    return "US".equalsIgnoreCase(getCountryCode(ip));
  }
}
