package cn.axzo.msg.center;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Target;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author cold_blade
 * @date 2023/10/19
 * @version 1.0
 */
@Slf4j
@Component
@Profile({"dev", "test", "local", "pre"})
public class FeignConfig implements RequestInterceptor, EnvironmentAware {
    private Environment environment;

    private static String POD_NAMESPACE;

    static {
        Map<String, String> env = System.getenv();
        if (env != null) {
            POD_NAMESPACE = env.get("MY_POD_NAMESPACE");
        }
        log.info("init FeignConfig, POD_NAMESPACE value is {}", POD_NAMESPACE);
    }

    @SneakyThrows
    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (POD_NAMESPACE == null) {
            Target<?> target = requestTemplate.feignTarget();
            String profile = environment.getProperty("spring.profiles.active");
            if (Objects.equals(profile, "dev")) {
                requestTemplate.target("http://dev-app.axzo.cn/" + target.name());
            } else if (Objects.equals(profile, "test")) {
                requestTemplate.target("http://test-api.axzo.cn/" + target.name());
            } else if (Objects.equals(profile, "pre")) {
                requestTemplate.target("http://pre-api.axzo.cn/" + target.name());
            }
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
