package example;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.postgresql.ds.PGSimpleDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class Connections {
    private Connections() {}

    public static String required(String key) {
        String value = System.getenv(key);
        if (value == null || value.isBlank()) throw new IllegalArgumentException("Missing " + key);
        return value;
    }

    public static HikariDataSource pool() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(required("LAB_DB_URL"));
        config.setUsername("lab_app");
        config.setPassword(required("LAB_APP_PASSWORD"));
        config.setMaximumPoolSize(1);
        config.setMinimumIdle(1);
        config.setConnectionTimeout(700);
        config.setValidationTimeout(300);
        config.setPoolName("pool-lab");
        config.addDataSourceProperty("connectTimeout", "3");
        config.addDataSourceProperty("socketTimeout", "5");
        config.addDataSourceProperty("ApplicationName", "pool-lab");
        return new HikariDataSource(config);
    }

    public static Connection independent() throws SQLException {
        PGSimpleDataSource source = new PGSimpleDataSource();
        source.setURL(required("LAB_DB_URL"));
        source.setUser("lab_app");
        source.setPassword(required("LAB_APP_PASSWORD"));
        source.setConnectTimeout(3);
        source.setSocketTimeout(5);
        source.setApplicationName("pool-lab-observer");
        return source.getConnection();
    }

    public static String scalar(Connection connection, String sql) throws SQLException {
        try (Statement statement = connection.createStatement();
             ResultSet rows = statement.executeQuery(sql)) {
            if (!rows.next()) throw new AssertionError("Query returned no row");
            return rows.getString(1);
        }
    }

    public static void execute(Connection connection, String sql) throws SQLException {
        try (Statement statement = connection.createStatement()) {
            statement.execute(sql);
        }
    }

    public static void require(boolean condition, String message) {
        if (!condition) throw new AssertionError(message);
    }
}
