use crate::documents::{RuntimeImportBlocker, RuntimeImportContext};
use crate::event::targets::RuntimeTerritoryTarget;
use crate::inspect::smp::events::SmpLoadedPackedEventConditionRowSummary;

pub(crate) fn lower_territory_target_in_condition(
    target: &RuntimeTerritoryTarget,
    row: &SmpLoadedPackedEventConditionRowSummary,
    runtime_context: &RuntimeImportContext,
) -> Result<RuntimeTerritoryTarget, RuntimeImportBlocker> {
    if !runtime_context.has_territory_context {
        return Err(RuntimeImportBlocker::MissingTerritoryContext);
    }
    if !row.requires_candidate_name_binding {
        return Ok(target.clone());
    }
    let candidate_name = row
        .candidate_name
        .as_ref()
        .ok_or(RuntimeImportBlocker::NamedTerritoryBinding)?;
    let territory_id = runtime_context
        .territory_name_to_id
        .get(candidate_name)
        .copied()
        .ok_or(RuntimeImportBlocker::NamedTerritoryBinding)?;
    Ok(RuntimeTerritoryTarget::Ids {
        ids: vec![territory_id],
    })
}
