use std::collections::HashMap;

use crate::datafile::experiment::Experiment;
use crate::datafile::feature_flag::FeatureFlag as InternalFeatureFlag;
use crate::datafile::rule::Rule as InternalRule;
use crate::datafile::variation_exposition::VariationByExposition;
use crate::types::Variation;

#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Rule {
    pub variations: HashMap<String, Variation>,
}

impl Rule {
    pub(crate) fn from_internal(rule: &impl InternalRule, feature_flag: &impl InternalFeatureFlag) -> Self {
        let experiment_id = rule.experiment().id();
        let variations = rule
            .experiment()
            .vars_by_exp()
            .iter()
            .filter_map(|var_by_exp| {
                feature_flag.get_variation(var_by_exp.variation_key()).map(|variation| {
                    (
                        var_by_exp.variation_key().to_owned(),
                        Variation::from_internal(variation, Some(var_by_exp.variation_id()), Some(experiment_id)),
                    )
                })
            })
            .collect();

        Self { variations }
    }
}
