package com.seer.teach.common.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.Map;

@Slf4j
@Configuration
@RefreshScope
public class NacosServiceMetadataRegistrationConfig {


    @Value("${server.servlet.context-path:}")
    private String contextPath;

    @Autowired
    private NacosDiscoveryProperties discoveryProperties;

    @PostConstruct
    public void registerContextPath() {
        // 将上下文根添加到服务元数据
        try {
            Map<String, String> metadata = discoveryProperties.getMetadata();
            metadata.put("context-path", contextPath);
            discoveryProperties.setMetadata(metadata);

            log.info("注册服务上下文根: {}", contextPath);
        } catch (Exception e) {
            log.error("注册服务上下文根失败", e);
        }
    }

    @PreDestroy
    public void cleanup() {
        log.info("清理Nacos服务元数据注册配置");
    }
}
