/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.config
 * @ClassName: PostgreSQLHealthIndicator
 * @Description: PostgreSQL健康检查指示器，用于Actuator健康检查
 * @Author: 张志锋
 * @Date: 2025-10-31
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * PostgreSQL 数据库健康检查指示器
 */
@Component("pgsqlHealthIndicator")
public class PostgreSQLHealthIndicator implements HealthIndicator {

    @Autowired
    private DataSource dataSource;

    @Override
    public Health health() {
        try (Connection connection = dataSource.getConnection()) {
            if (connection.isValid(1)) {
                // 可以执行一个简单的查询来验证连接
                try (java.sql.Statement stmt = connection.createStatement();
                     java.sql.ResultSet rs = stmt.executeQuery("SELECT version()")) {
                    if (rs.next()) {
                        String version = rs.getString(1);
                        return Health.up()
                                .withDetail("database", "PostgreSQL")
                                .withDetail("status", "连接正常")
                                .withDetail("version", version)
                                .build();
                    }
                }
                return Health.up()
                        .withDetail("database", "PostgreSQL")
                        .withDetail("status", "连接正常")
                        .build();
            } else {
                return Health.down()
                        .withDetail("database", "PostgreSQL")
                        .withDetail("status", "连接无效")
                        .build();
            }
        } catch (SQLException e) {
            return Health.down()
                    .withDetail("database", "PostgreSQL")
                    .withDetail("status", "连接失败")
                    .withDetail("error", e.getMessage())
                    .build();
        }
    }
}

