use std::fmt::{Debug, Error, Formatter};

use crate::targeting::{models::SegmentModel, targeting_tree::TargetingTree};

#[cfg_attr(test, mockall::automock)]
pub(crate) trait Segment: Send + Sync + Debug {
    fn id(&self) -> u32;
    fn audience_tracking(&self) -> bool;
    fn tree<'a>(&'a self) -> Option<&'a TargetingTree>;
}

pub(crate) struct SegmentImpl {
    id: u32,
    audience_tracking: bool,
    tree: Option<TargetingTree>,
}

impl Segment for SegmentImpl {
    fn id(&self) -> u32 {
        self.id
    }

    fn audience_tracking(&self) -> bool {
        return self.audience_tracking;
    }

    fn tree(&self) -> Option<&TargetingTree> {
        return self.tree.as_ref();
    }
}

impl From<SegmentModel> for SegmentImpl {
    fn from(model: SegmentModel) -> Self {
        Self {
            id: model.id,
            audience_tracking: model.audience_tracking.unwrap_or(false),
            tree: TargetingTree::from_json(model.condition_data),
        }
    }
}

impl Debug for SegmentImpl {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        f.debug_struct("Segment").field("id", &self.id).field("audience_tracking", &self.audience_tracking).finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::datafile::datafile_test_utils::make_segment_dto;

    #[test]
    fn test_segment_impl_from() {
        // Arrange
        let dto = make_segment_dto(42, true);
        // Act
        let segment_impl = SegmentImpl::from(dto.clone());
        // Assert
        assert_eq!(segment_impl.id(), 42);
        assert!(segment_impl.audience_tracking());
    }
}
