/// Tests for the Postgres athena provisioning pipeline.
///
/// These tests verify the embedded provision SQL is valid (non-empty, parseable)
/// and that the CLI arg types are wired correctly, without requiring a live
/// Postgres connection.

/// Verify the provision SQL is bundled and contains the expected tables.
#[test]
fn provision_sql_contains_required_tables() {
    let sql = include_str!("../sql/provision.sql");
    assert!(!sql.is_empty(), "provision.sql must not be empty");

    let required_tables = [
        "gateway_request_log",
        "gateway_operation_log",
        "api_keys",
        "api_key_rights",
        "api_key_right_grants",
        "api_key_config",
        "api_key_client_config",
        "api_key_auth_log",
        "athena_clients",
        "client_statistics",
        "client_table_statistics",
        "query_history",
        "saved_queries",
        "ui_request_log",
        "feedback",
        "organization_requests",
        "project_requests",
    ];

    for table in &required_tables {
        assert!(
            sql.contains(table),
            "provision.sql must contain table '{table}'"
        );
    }
}

/// Verify every CREATE TABLE statement uses IF NOT EXISTS (idempotency).
#[test]
fn provision_sql_uses_if_not_exists() {
    let sql = include_str!("../sql/provision.sql");
    for line in sql.lines() {
        let upper = line.trim().to_uppercase();
        if upper.starts_with("CREATE TABLE") {
            assert!(
                upper.contains("IF NOT EXISTS"),
                "All CREATE TABLE statements must use IF NOT EXISTS. Offending line: {line}"
            );
        }
    }
}

/// Verify every CREATE INDEX statement uses IF NOT EXISTS (idempotency).
#[test]
fn provision_sql_indexes_use_if_not_exists() {
    let sql = include_str!("../sql/provision.sql");
    for line in sql.lines() {
        let upper = line.trim().to_uppercase();
        if upper.starts_with("CREATE INDEX") || upper.starts_with("CREATE UNIQUE INDEX") {
            assert!(
                upper.contains("IF NOT EXISTS"),
                "All CREATE INDEX statements must use IF NOT EXISTS. Offending line: {line}"
            );
        }
    }
}

/// Smoke-test that splitting the SQL by `;` produces reasonable statement count.
#[test]
fn provision_sql_has_expected_statement_count() {
    let sql = include_str!("../sql/provision.sql");
    let count = sql
        .split(';')
        .map(str::trim)
        .filter(|s| !s.is_empty() && !s.starts_with("--"))
        .count();
    // We expect at least 20 statements (tables + indexes + inserts).
    assert!(
        count >= 20,
        "provision.sql should have at least 20 statements, found {count}"
    );
}
