package com.seer.teach.user.admin.service;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.seer.teach.user.admin.dto.ServiceInfoDTO;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SeerNacosServiceDiscovery {

    private NacosDiscoveryProperties discoveryProperties;

    public SeerNacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties) {
        this.discoveryProperties = discoveryProperties;
    }

    public List<ServiceInfoDTO> getAppServices() {
        try {
            NamingService namingService = discoveryProperties.namingServiceInstance();
            ListView<String> services = namingService.getServicesOfServer(1, Integer.MAX_VALUE);

            return services.getData().stream()
                    .map(service -> new ServiceInfoDTO(service, getServiceMetadata(service)))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            throw new RuntimeException("获取Nacos服务列表失败", e);
        }
    }

    public Instance getAppServicesByServiceName(String serviceName) {
        try {
            NamingService namingService = discoveryProperties.namingServiceInstance();
            return namingService.selectOneHealthyInstance(serviceName);
        } catch (Exception e) {
            throw new RuntimeException("获取Nacos服务列表失败", e);
        }
    }

    private Map<String, String> getServiceMetadata(String serviceName) {
        try {
            List<Instance> instances = discoveryProperties.namingServiceInstance()
                    .getAllInstances(serviceName);
            return instances.isEmpty() ? Collections.emptyMap() : instances.get(0).getMetadata();
        } catch (Exception e) {
            return Collections.emptyMap();
        }
    }
}