/// Integration tests for the Athena provisioning API endpoints.
///
/// These tests verify the provision module's helper logic and the expected-table
/// list without requiring a live database.  The full HTTP endpoint is covered by
/// the `EXPECTED_TABLES` constant alignment and the SQL parsing tests in
/// `tests/provision.rs`.
///
/// The provision module's expected-table list must match the tables defined in
/// the SQL provisioning script.
#[test]
fn expected_tables_list_matches_provision_sql() {
    let sql = include_str!("../sql/provision.sql");

    let expected_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",
        "client_alert_queries",
        "query_history",
        "saved_queries",
        "ui_request_log",
        "feedback",
        "organization_requests",
        "project_requests",
    ];

    for table in &expected_tables {
        let pattern: String = "CREATE TABLE IF NOT EXISTS".to_string();
        let found: bool = sql.lines().any(|line| {
            let upper: String = line.trim().to_uppercase();
            upper.contains(&pattern) && line.contains(table)
        });
        assert!(
            found,
            "provision.sql must have a CREATE TABLE IF NOT EXISTS for '{table}'"
        );
    }
}

/// Splitting provision SQL by semicolons must produce runnable non-empty
/// statements (same logic the API handler uses).
#[test]
fn provision_sql_splitting_produces_valid_statements() {
    let sql = include_str!("../sql/provision.sql");
    let statements: Vec<&str> = sql
        .split(';')
        .map(str::trim)
        .filter(|s| !s.is_empty() && !s.starts_with("--"))
        .collect();

    assert!(
        statements.len() >= 20,
        "expected >= 20 statements, got {}",
        statements.len()
    );

    for (i, stmt) in statements.iter().enumerate() {
        let upper: String = stmt.to_uppercase();
        let valid_prefix: bool = upper.starts_with("CREATE")
            || upper.starts_with("INSERT")
            || upper.starts_with("ALTER")
            || upper.starts_with("DROP")
            || upper.starts_with("SELECT")
            || upper.starts_with("SET")
            || upper.starts_with("DO ");
        assert!(
            valid_prefix,
            "Statement {} does not start with a recognized SQL keyword: {}",
            i + 1,
            &stmt[..stmt.len().min(80)]
        );
    }
}

/// The `client_alert_queries` table (added later) must be present.
#[test]
fn provision_sql_includes_client_alert_queries() {
    let sql = include_str!("../sql/provision.sql");
    assert!(
        sql.contains("client_alert_queries"),
        "provision.sql must include client_alert_queries"
    );
}
