use super::super::condition_targets::{
    ensure_condition_true_chairman_context, lower_condition_targets_in_effect,
    lowered_condition_true_company_target, lowered_condition_true_player_target,
    packed_record_condition_scope_import_blocker,
};
use super::super::contextual_effects::lower_contextual_real_grouped_effects;
use crate::documents::{RuntimeImportBlocker, RuntimeImportContext};
use crate::event::effects::RuntimeEffect;
use crate::inspect::smp::events::SmpLoadedPackedEventRecordSummary;

pub(crate) fn lowered_record_decoded_actions(
    record: &SmpLoadedPackedEventRecordSummary,
    runtime_context: &RuntimeImportContext,
) -> Result<Vec<RuntimeEffect>, RuntimeImportBlocker> {
    if let Some(blocker) = packed_record_condition_scope_import_blocker(record, runtime_context) {
        return Err(blocker);
    }
    ensure_condition_true_chairman_context(record)?;

    let lowered_company_target = lowered_condition_true_company_target(record)?;
    let lowered_player_target = lowered_condition_true_player_target(record)?;
    let base_effects = if record.payload_family != "real_packed_v1"
        || record.decoded_actions.len() == record.grouped_effect_rows.len()
    {
        record.decoded_actions.clone()
    } else {
        lower_contextual_real_grouped_effects(record, runtime_context)?
    };
    base_effects
        .iter()
        .map(|effect| {
            lower_condition_targets_in_effect(
                effect,
                lowered_company_target.as_ref(),
                lowered_player_target.as_ref(),
            )
        })
        .collect()
}
