use crate::engine::conditions::ResolvedConditionContext;
use crate::engine::metrics::retire_matching_trains;
use crate::engine::targets::{resolve_company_target_ids, resolve_territory_target_ids};
use crate::event::targets::{RuntimeCompanyTarget, RuntimeTerritoryTarget};
use crate::state::RuntimeState;

pub(super) fn apply_retire_trains(
    state: &mut RuntimeState,
    company_target: Option<&RuntimeCompanyTarget>,
    territory_target: Option<&RuntimeTerritoryTarget>,
    locomotive_name: Option<&str>,
    condition_context: &ResolvedConditionContext,
) -> Result<(), String> {
    let company_ids = company_target
        .map(|target| resolve_company_target_ids(state, target, condition_context))
        .transpose()?;
    let territory_ids = territory_target
        .map(|target| resolve_territory_target_ids(state, target))
        .transpose()?;
    retire_matching_trains(
        &mut state.trains,
        company_ids.as_ref(),
        territory_ids.as_ref(),
        locomotive_name,
    );
    Ok(())
}
