/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */

package net.yyc.common.gray.ribbon;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.ConditionalOnRibbonNacos;
import com.alibaba.cloud.nacos.ribbon.NacosRibbonClientConfiguration;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.ribbon.PropertiesFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 覆盖默认 {@link com.alibaba.cloud.nacos.ribbon.NacosServerList}，支持跨 Group 发现。
 * 仅通过 {@link NacosCrossGroupRibbonAutoConfiguration} 的 {@code @RibbonClients} 导入 Ribbon 子上下文。
 *
 * @author hnqz
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnRibbonNacos
public class NacosCrossGroupRibbonClientConfiguration extends NacosRibbonClientConfiguration {

	@Autowired
	private PropertiesFactory propertiesFactory;

	@Bean
	@SuppressWarnings("rawtypes")
	public ServerList ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties,
			Environment environment) {
		if (this.propertiesFactory.isSet(ServerList.class, config.getClientName())) {
			return this.propertiesFactory.get(ServerList.class, config, config.getClientName());
		}
		NacosCrossGroupServerList serverList = new NacosCrossGroupServerList(nacosDiscoveryProperties, environment);
		serverList.initWithNiwsConfig(config);
		return serverList;
	}

}
