package com.ys.graph.sync.config;

import com.vesoft.nebula.driver.graph.net.NebulaPool;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * NebulaGraph 连接池配置
 * 配置项前缀: nebula.graph
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "nebula.graph")
public class NebulaGraphConfig {

    /** NebulaGraph 服务地址，格式：host1:port1,host2:port2 */
    private String addresses;

    /** 用户名 */
    private String username;

    /** 密码 */
    private String password;

    /** 连接超时时间（毫秒） */
    private int connectTimeoutMills;

    /** 请求超时时间（毫秒） */
    private int requestTimeoutMills;

    /** 最大连接数 */
    private int maxClientSize;

    /** 最小连接数 */
    private int minClientSize;

    /** 连接池健康检查间隔（毫秒） */
    private long healthCheckTimeMills = 60000;

    /** 连接最大生命周期（毫秒） */
    private long maxLifeTimeMs = 600000;

    private NebulaPool nebulaPool;

    @Bean
    public NebulaPool nebulaPool() {
        try {
            log.info("Initializing NebulaGraph connection pool, addresses: {}", addresses);
            nebulaPool = NebulaPool.builder(addresses, username, password)
                    .withConnectTimeoutMills(connectTimeoutMills)
                    .withRequestTimeoutMills(requestTimeoutMills)
                    .withMaxClientSize(maxClientSize)
                    .withMinClientSize(minClientSize)
                    .withHealthCheckTimeMills(healthCheckTimeMills)
                    .withMaxLifeTimeMs(maxLifeTimeMs)
                    .withBlockWhenExhausted(true)
                    .withMaxWaitMills(Long.MAX_VALUE)
                    .build();
            log.info("NebulaGraph connection pool initialized successfully");
            return nebulaPool;
        } catch (Exception e) {
            log.error("Failed to initialize NebulaGraph connection pool", e);
            throw new RuntimeException("Failed to initialize NebulaGraph connection pool", e);
        }
    }

    @PreDestroy
    public void destroy() {
        if (nebulaPool != null) {
            log.info("Closing NebulaGraph connection pool");
            nebulaPool.close();
        }
    }
}
