use std::collections::BTreeSet;

use crate::event::targets::RuntimeTerritoryTarget;
use crate::state::RuntimeState;

use super::shared;

pub(in crate::engine) fn resolve_territory_target_ids(
    state: &RuntimeState,
    target: &RuntimeTerritoryTarget,
) -> Result<Vec<u32>, String> {
    match target {
        RuntimeTerritoryTarget::AllTerritories => Ok(state
            .territories
            .iter()
            .map(|territory| territory.territory_id)
            .collect()),
        RuntimeTerritoryTarget::Ids { ids } => {
            let known_ids = state
                .territories
                .iter()
                .map(|territory| territory.territory_id)
                .collect::<BTreeSet<_>>();
            shared::validate_known_ids(ids, &known_ids, |territory_id| {
                format!("territory target references unknown territory_id {territory_id}")
            })?;
            Ok(ids.clone())
        }
    }
}
