package example.obrh;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;

/** UCP API illustration. Reconcile an existing JNDI owner; don't create a duplicate pool. */
public final class UcpPoolExample {
    private UcpPoolExample() { }

    public static PoolDataSource configure(String jdbcUrl, String username, String password)
            throws SQLException {
        PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource();
        pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
        pool.setURL(jdbcUrl); // Credentials supplied by approved secret handling.
        pool.setUser(username);
        pool.setPassword(password);
        pool.setConnectionPoolName("example-application-pool");
        pool.setInitialPoolSize(2);
        pool.setMinPoolSize(2);
        pool.setMaxPoolSize(12); // Illustrative per-physical-pool session allocation.
        pool.setConnectionWaitTimeout(1); // Seconds, wait for pool connection availability.
        pool.setValidateConnectionOnBorrow(true);
        pool.setSQLForValidateConnection("SELECT 1 FROM DUAL");
        return pool; // Application/container owner must manage shutdown/drain.
    }

    public static boolean readOnlyProbe(PoolDataSource pool) throws SQLException {
        // Borrow inside endpoint admission; no connection held while calling provider.
        try (Connection connection = pool.getConnection();
             PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM DUAL")) {
            statement.setQueryTimeout(1); // Seconds; driver/database cancellation semantics.
            try (ResultSet rows = statement.executeQuery()) {
                return rows.next() && rows.getInt(1) == 1;
            }
        } // close() returns borrowed connection to pool, including exception paths.
    }
    // Pool wait is separate from physical login/connect, SQL, transaction and network
    // timeouts. Budget each against the remaining logical-request deadline.
    // This generic SELECT is NOT the existing OBRH DB/Camel health-check implementation.
}
