use crate::state::RuntimeState;

pub(super) fn validate_metadata(state: &RuntimeState) -> Result<(), String> {
    for key in state.world_flags.keys() {
        if key.trim().is_empty() {
            return Err("world_flags contains an empty key".to_string());
        }
    }

    for (label, value) in [
        (
            "save_profile.profile_kind",
            state.save_profile.profile_kind.as_deref(),
        ),
        (
            "save_profile.profile_family",
            state.save_profile.profile_family.as_deref(),
        ),
        (
            "save_profile.map_path",
            state.save_profile.map_path.as_deref(),
        ),
        (
            "save_profile.display_name",
            state.save_profile.display_name.as_deref(),
        ),
    ] {
        if value.is_some_and(|text| text.trim().is_empty()) {
            return Err(format!("{label} must not be empty"));
        }
    }

    if state.world_restore.selected_year_profile_lane.is_none()
        && (state.world_restore.campaign_scenario_enabled.is_some()
            || state.world_restore.sandbox_enabled.is_some())
    {
        return Err(
            "world_restore.selected_year_profile_lane must be present when world restore flags are populated"
                .to_string(),
        );
    }

    if state
        .world_restore
        .absolute_counter_restore_kind
        .as_deref()
        .is_some_and(|text| text.trim().is_empty())
    {
        return Err("world_restore.absolute_counter_restore_kind must not be empty".to_string());
    }
    if state
        .world_restore
        .absolute_counter_adjustment_context
        .as_deref()
        .is_some_and(|text| text.trim().is_empty())
    {
        return Err(
            "world_restore.absolute_counter_adjustment_context must not be empty".to_string(),
        );
    }
    for (key, value) in &state.metadata {
        if key.trim().is_empty() {
            return Err("metadata contains an empty key".to_string());
        }
        if value.trim().is_empty() {
            return Err(format!("metadata[{key}] must not be empty"));
        }
    }

    Ok(())
}
