//! GEO API command handlers.

use crate::api::client::GdeltClient;
use crate::api::geo::{GeoApi, GeoSearchParams, GeoPointsParams, GeoHeatmapParams, GeoAggregateParams};
use crate::cli::args::{GeoCommand, GlobalArgs, AggregationLevel};
use crate::cli::output::OutputWriter;
use crate::error::{ExitStatus, Result};
use std::time::Duration;

/// Handle GEO commands
pub async fn handle_geo(cmd: GeoCommand, global: &GlobalArgs) -> Result<ExitStatus> {
    let client = GdeltClient::with_timeout(Duration::from_secs(global.timeout))?;
    let api = GeoApi::new(client);

    match cmd {
        GeoCommand::Search(args) => {
            let params = GeoSearchParams {
                query: args.query,
                timespan: Some(args.timespan),
                location: args.location,
                country: args.country,
                max_points: Some(args.max_points),
            };

            let response = api.search(params).await?;
            let output = OutputWriter::new(global);
            output.write_value(&response)?;

            Ok(ExitStatus::Success)
        }

        GeoCommand::Points(args) => {
            let params = GeoPointsParams {
                query: args.query,
                timespan: Some(args.timespan),
                resolution: Some(args.resolution),
            };

            let response = api.points(params).await?;
            let output = OutputWriter::new(global);
            output.write_value(&response)?;

            Ok(ExitStatus::Success)
        }

        GeoCommand::Heatmap(args) => {
            let params = GeoHeatmapParams {
                query: args.query,
                timespan: Some(args.timespan),
            };

            let response = api.heatmap(params).await?;
            let output = OutputWriter::new(global);
            output.write_value(&response)?;

            Ok(ExitStatus::Success)
        }

        GeoCommand::Aggregate(args) => {
            let level = match args.level {
                AggregationLevel::Country => "country",
                AggregationLevel::Adm1 => "adm1",
            };

            let params = GeoAggregateParams {
                query: args.query,
                level: Some(level.to_string()),
                timespan: Some(args.timespan),
            };

            let response = api.aggregate(params).await?;
            let output = OutputWriter::new(global);
            output.write_value(&response)?;

            Ok(ExitStatus::Success)
        }
    }
}
