use crate::engine::metrics::{compare_condition_value, territory_metric_value};
use crate::engine::targets::resolve_territory_target_ids;
use crate::event::conditions::RuntimeConditionComparator;
use crate::event::metrics::RuntimeTerritoryMetric;
use crate::event::targets::RuntimeTerritoryTarget;
use crate::state::RuntimeState;

pub(super) fn territory_numeric_threshold_matches(
    state: &RuntimeState,
    target: &RuntimeTerritoryTarget,
    metric: RuntimeTerritoryMetric,
    comparator: RuntimeConditionComparator,
    value: i64,
) -> Result<bool, String> {
    let territory_ids = resolve_territory_target_ids(state, target)?;
    let actual = territory_metric_value(state, &territory_ids, metric);
    Ok(compare_condition_value(actual, comparator, value))
}

pub(super) fn territory_variable_threshold_matches(
    state: &RuntimeState,
    target: &RuntimeTerritoryTarget,
    index: u32,
    comparator: RuntimeConditionComparator,
    value: i64,
) -> Result<bool, String> {
    let territory_ids = resolve_territory_target_ids(state, target)?;
    let actual = territory_ids
        .iter()
        .map(|territory_id| {
            state
                .territory_runtime_variables
                .get(territory_id)
                .and_then(|vars| vars.get(&index))
                .copied()
                .unwrap_or(0)
        })
        .sum::<i64>();
    Ok(compare_condition_value(actual, comparator, value))
}
