/*
 *    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.ribbon.RibbonNacosAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 排除官方 {@link RibbonNacosAutoConfiguration}，避免 Ribbon 子上下文重复注册
 * {@code NacosRibbonClientConfiguration} 导致跨 Group ServerList 无法生效。
 *
 * @author hnqz
 */
public class NacosCrossGroupEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {

	private static final String EXCLUDE_KEY = "spring.autoconfigure.exclude";

	private static final String EXCLUDE_TARGET = RibbonNacosAutoConfiguration.class.getName();

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		String existing = environment.getProperty(EXCLUDE_KEY, "");
		if (containsExclude(existing, EXCLUDE_TARGET)) {
			return;
		}
		String merged = StringUtils.hasText(existing) ? existing + "," + EXCLUDE_TARGET : EXCLUDE_TARGET;
		Map<String, Object> source = new HashMap<>(1);
		source.put(EXCLUDE_KEY, merged);
		environment.getPropertySources().addFirst(new MapPropertySource("nacosCrossGroupAutoConfigureExclude", source));
	}

	private boolean containsExclude(String existing, String target) {
		if (!StringUtils.hasText(existing)) {
			return false;
		}
		for (String item : existing.split(",")) {
			if (target.equals(StringUtils.trimWhitespace(item))) {
				return true;
			}
		}
		return false;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

}
