use athena_rs::api::gateway::fetch::{
    AggregationStrategy, PostProcessingConfig, apply_post_processing,
};
use serde_json::json;

#[test]
fn post_processing_config_from_body_normalizes_columns() {
    let body = json!({
        "group_by": "CreatedAt",
        "aggregation_column": "TotalValue",
        "aggregation_strategy": "cumulative_sum"
    });
    let config = PostProcessingConfig::from_body(Some(&body), true);
    assert_eq!(config.group_by.as_deref(), Some("created_at"));
    assert_eq!(config.aggregation_column.as_deref(), Some("total_value"));
    assert_eq!(
        config.aggregation_strategy,
        Some(AggregationStrategy::CumulativeSum)
    );
}

#[test]
fn apply_post_processing_requires_aggregation_column() {
    let rows = vec![json!({"created_at": "2024-01-01T00:00:00Z", "value": 1})];
    let config = PostProcessingConfig {
        group_by: Some("created_at".to_string()),
        time_granularity: None,
        aggregation_column: None,
        aggregation_strategy: Some(AggregationStrategy::CumulativeSum),
        dedup_aggregation: false,
    };
    let result = apply_post_processing(&rows, &config);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .contains("aggregation_strategy requires aggregation_column")
    );
}

#[test]
fn apply_post_processing_groups_rows() {
    let rows = vec![
        json!({"created_at": "2024-01-01T00:00:00Z", "value": 2}),
        json!({"created_at": "2024-01-01T00:00:00Z", "value": 3}),
    ];
    let config = PostProcessingConfig {
        group_by: Some("created_at".to_string()),
        time_granularity: None,
        aggregation_column: Some("value".to_string()),
        aggregation_strategy: Some(AggregationStrategy::CumulativeSum),
        dedup_aggregation: false,
    };
    let grouped = apply_post_processing(&rows, &config)
        .expect("Grouping should succeed")
        .expect("Grouping payload should exist");
    assert!(grouped.get("grouped").is_some());
}
