package com.cameleer.server.app.search;

import com.cameleer.server.app.ClickHouseTestHelper;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.testcontainers.clickhouse.ClickHouseContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@Testcontainers
class AlertingProjectionsIT {

    @Container
    static final ClickHouseContainer clickhouse =
            new ClickHouseContainer("clickhouse/clickhouse-server:24.12");

    private JdbcTemplate jdbc;

    @BeforeEach
    void setUp() throws Exception {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(clickhouse.getJdbcUrl());
        ds.setUsername(clickhouse.getUsername());
        ds.setPassword(clickhouse.getPassword());

        jdbc = new JdbcTemplate(ds);
        ClickHouseTestHelper.executeInitSqlWithProjections(jdbc);
    }

    @Test
    void allFourProjectionsExistAfterInit() {
        // logs and agent_metrics are plain MergeTree — always succeed.
        // executions is ReplacingMergeTree; its projections now succeed because
        // alerting_projections.sql runs ALTER TABLE executions MODIFY SETTING
        // deduplicate_merge_projection_mode='rebuild' before the ADD PROJECTION statements.
        List<String> names = jdbc.queryForList(
                "SELECT name FROM system.projections WHERE table IN ('logs', 'agent_metrics', 'executions')",
                String.class);

        assertThat(names).containsExactlyInAnyOrder(
                "alerting_app_level",
                "alerting_instance_metric",
                "alerting_app_status",
                "alerting_route_status");
    }
}
