/*
 *    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.NacosServer;
import com.alibaba.cloud.nacos.ribbon.NacosServerList;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import cn.hutool.core.util.StrUtil;
import com.netflix.client.config.IClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;

/**
 * 支持按 {@code yyc.nacos.cross-group.{serviceId}} 跨 Nacos Group 拉取实例。
 *
 * @author hnqz
 */
@Slf4j
public class NacosCrossGroupServerList extends NacosServerList {

	private static final String CROSS_GROUP_PREFIX = "yyc.nacos.cross-group.";

	private final NacosDiscoveryProperties discoveryProperties;

	private final Environment environment;

	private String serviceId;

	public NacosCrossGroupServerList(NacosDiscoveryProperties discoveryProperties, Environment environment) {
		super(discoveryProperties);
		this.discoveryProperties = discoveryProperties;
		this.environment = environment;
	}

	@Override
	public void initWithNiwsConfig(IClientConfig iClientConfig) {
		super.initWithNiwsConfig(iClientConfig);
		this.serviceId = iClientConfig.getClientName();
	}

	@Override
	public List<NacosServer> getInitialListOfServers() {
		return resolveServers();
	}

	@Override
	public List<NacosServer> getUpdatedListOfServers() {
		return resolveServers();
	}

	private List<NacosServer> resolveServers() {
		String resolvedServiceId = serviceId != null ? serviceId : getServiceId();
		String targetGroup = resolveTargetGroup(resolvedServiceId);
		try {
			List<Instance> instances = discoveryProperties.namingServiceInstance()
				.selectInstances(resolvedServiceId, targetGroup, true);
			List<NacosServer> servers = instancesToServerList(instances);
			log.debug("Nacos cross-group server list: serviceId={}, targetGroup={}, count={}", resolvedServiceId,
					targetGroup, servers.size());
			return servers;
		}
		catch (Exception e) {
			throw new IllegalStateException("Can not get service instances from nacos, serviceId=" + resolvedServiceId
					+ ", group=" + targetGroup, e);
		}
	}

	private String resolveTargetGroup(String resolvedServiceId) {
		String targetGroup = environment.getProperty(CROSS_GROUP_PREFIX + resolvedServiceId);
		if (StrUtil.isNotBlank(targetGroup)) {
			return targetGroup;
		}
		return discoveryProperties.getGroup();
	}

	private List<NacosServer> instancesToServerList(List<Instance> instances) {
		List<NacosServer> result = new ArrayList<>();
		if (CollectionUtils.isEmpty(instances)) {
			return result;
		}
		for (Instance instance : instances) {
			result.add(new NacosServer(instance));
		}
		return result;
	}

}
