package com.cameleer.server.app;

import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Loads and executes the consolidated ClickHouse init.sql schema for integration tests.
 */
public final class ClickHouseTestHelper {

    private ClickHouseTestHelper() {}

    public static void executeInitSql(JdbcTemplate jdbc) throws IOException {
        executeScript(jdbc, "clickhouse/init.sql");
    }

    public static void executeInitSqlWithProjections(JdbcTemplate jdbc) throws IOException {
        executeScript(jdbc, "clickhouse/init.sql");
        executeScript(jdbc, "clickhouse/alerting_projections.sql");
    }

    private static void executeScript(JdbcTemplate jdbc, String classpathResource) throws IOException {
        String sql = new ClassPathResource(classpathResource)
                .getContentAsString(StandardCharsets.UTF_8);
        for (String statement : sql.split(";")) {
            String trimmed = statement.trim();
            String withoutComments = trimmed.lines()
                    .filter(line -> !line.stripLeading().startsWith("--"))
                    .map(String::trim)
                    .filter(line -> !line.isEmpty())
                    .reduce("", (a, b) -> a + b);
            if (!withoutComments.isEmpty()) {
                String upper = withoutComments.toUpperCase();
                boolean isBestEffort = upper.contains("MATERIALIZE PROJECTION")
                        || upper.contains("ADD PROJECTION");
                try {
                    jdbc.execute(trimmed);
                } catch (Exception e) {
                    if (isBestEffort) {
                        // ADD PROJECTION on ReplacingMergeTree requires a session setting unavailable
                        // via JDBC pool; MATERIALIZE can fail on empty tables — both non-fatal in tests.
                        System.err.println("Projection DDL skipped (non-fatal): " + e.getMessage());
                    } else {
                        throw e;
                    }
                }
            }
        }
    }
}
