use crate::{
    datafile::datafile::DataFile,
    targeting::{TargetingData, conditions::TargetingCondition, models::TargetExperimentCPModel},
};

enum VariationMatchType {
    Any,
    Exact { variation_id: u32 },
}

pub(crate) struct TargetExperimentCondition {
    experiment_id: u32,
    variation_match_type: VariationMatchType,
}

impl TargetExperimentCondition {
    pub fn from_json(model: TargetExperimentCPModel) -> Option<Self> {
        let variation_match_type = match model.variation_match_type.as_str() {
            "ANY" => VariationMatchType::Any,
            "EXACT" => VariationMatchType::Exact {
                variation_id: model.variation_id?,
            },
            _ => return None,
        };
        return Some(Self {
            experiment_id: model.experiment_id,
            variation_match_type,
        });
    }
}

impl TargetingCondition for TargetExperimentCondition {
    fn check(&self, data: &TargetingData<impl DataFile>) -> Option<bool> {
        let variation = data.visitor_data.assigned_variations.r().get(&self.experiment_id)?;
        Some(match self.variation_match_type {
            VariationMatchType::Any => true,
            VariationMatchType::Exact { variation_id } => variation.variation_id == variation_id,
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        data::{BaseData, assigned_variation::AssignedVariation},
        datafile::{datafile_test_utils::MockDataFile, rule::RuleType},
        storage::visitor::Visitor,
        targeting::TargetingDataBuilder,
        utils::test_utils::assert_targeting,
    };

    use rstest::rstest;

    fn new_var(exp_id: u32, var_id: u32) -> AssignedVariation {
        return AssignedVariation::new(exp_id, var_id, RuleType::Unknown);
    }

    #[rstest]
    #[case(None, false)]
    #[case(Some(vec![]), false)]
    #[case(Some(vec![new_var(0, 1)]), false)]
    #[case(Some(vec![new_var(1, 10)]), true)]
    #[case(Some(vec![new_var(1, 20)]), true)]
    #[case(Some(vec![new_var(2, 10)]), false)]
    #[case(Some(vec![new_var(2, 20)]), true)]
    fn test_check(#[case] assigned_variations: Option<Vec<AssignedVariation>>, #[case] expected: bool) {
        let datafile = MockDataFile::default();
        let visitor = Visitor::new();
        if let Some(assigned_variations) = assigned_variations {
            visitor.add_data(assigned_variations.into_iter().map(|av| BaseData::AssignedVariation(av)), true);
        }
        assert_targeting(
            "resources/conditions/mock_segment_target_experiment.json",
            &TargetingDataBuilder::new().build(&datafile, &visitor.rdata()),
            expected,
        );
    }
}
