package com.lanyuanxiaoyao.service.forest.configuration;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.dtflys.forest.auth.BasicAuth;
import com.dtflys.forest.http.ForestAddress;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import com.lanyuanxiaoyao.service.common.Constants;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

/**
 * @author lanyuanxiaoyao
 * @date 2023-04-24
 */
@Component
public class SpringCloudDiscoveryInterceptor implements Interceptor<Object> {
    private static final Logger logger = LoggerFactory.getLogger(SpringCloudDiscoveryInterceptor.class);

    private final LoadBalancerClient loadBalancerClient;

    public SpringCloudDiscoveryInterceptor(LoadBalancerClient loadBalancerClient) {
        this.loadBalancerClient = loadBalancerClient;
    }

    @Override
    public boolean beforeExecute(ForestRequest request) {
        // Load
        URL url = URLUtil.url(request.getUrl());
        String host = url.getHost();
        if (StrUtil.isNotBlank(host)) {
            ServiceInstance instance = loadBalancerClient.choose(host);
            if (ObjectUtil.isNotNull(instance)) {
                request.setAddress(new ForestAddress(instance.getScheme(), instance.getHost(), instance.getPort()));
            }
        }

        // Basic auth
        BasicAuth basicAuth = new BasicAuth(Constants.SPRING_SECURITY_USERNAME, Constants.SPRING_SECURITY_PASSWORD_PLAIN);
        basicAuth.enhanceAuthorization(request);

        return Interceptor.super.beforeExecute(request);
    }
}
