use crate::engine::effects::EventGraphMutation;
use crate::state::RuntimeState;

pub(super) fn commit_staged_event_graph_mutations(
    state: &mut RuntimeState,
    staged_event_graph_mutations: &[EventGraphMutation],
) -> Result<(), String> {
    for mutation in staged_event_graph_mutations {
        match mutation {
            EventGraphMutation::Append(record) => {
                if state
                    .event_runtime_records
                    .iter()
                    .any(|existing| existing.record_id == record.record_id)
                {
                    return Err(format!(
                        "cannot append duplicate event record_id {}",
                        record.record_id
                    ));
                }
                state
                    .event_runtime_records
                    .push(record.clone().into_runtime_record());
            }
            EventGraphMutation::Activate { record_id } => {
                let record = state
                    .event_runtime_records
                    .iter_mut()
                    .find(|record| record.record_id == *record_id)
                    .ok_or_else(|| {
                        format!("cannot activate missing event record_id {record_id}")
                    })?;
                record.active = true;
            }
            EventGraphMutation::Deactivate { record_id } => {
                let record = state
                    .event_runtime_records
                    .iter_mut()
                    .find(|record| record.record_id == *record_id)
                    .ok_or_else(|| {
                        format!("cannot deactivate missing event record_id {record_id}")
                    })?;
                record.active = false;
            }
            EventGraphMutation::Remove { record_id } => {
                let index = state
                    .event_runtime_records
                    .iter()
                    .position(|record| record.record_id == *record_id)
                    .ok_or_else(|| format!("cannot remove missing event record_id {record_id}"))?;
                state.event_runtime_records.remove(index);
            }
        }
    }

    state.validate()
}
