//! Creator entity type.

use std::collections::HashMap;

use crate::schema::EntityId;

/// A creator entity in tidalDB.
///
/// Creators produce items. They have metadata (name, description) and an
/// optional embedding (catalog vector, database-managed).
#[derive(Debug, Clone)]
pub struct CreatorEntity {
    pub creator_id: EntityId,
    pub metadata: HashMap<String, String>,
    pub embedding: Option<Vec<f32>>,
}

impl CreatorEntity {
    #[must_use]
    pub fn new(creator_id: EntityId) -> Self {
        Self {
            creator_id,
            metadata: HashMap::new(),
            embedding: None,
        }
    }

    /// Serialize to bytes using the shared entity codec.
    #[must_use]
    pub fn serialize(&self) -> Vec<u8> {
        super::serialize_entity(self.embedding.as_deref(), &self.metadata)
    }

    /// Deserialize from bytes.
    #[must_use]
    pub fn deserialize(creator_id: EntityId, bytes: &[u8]) -> Self {
        let (embedding, metadata) = super::deserialize_entity(bytes);
        Self {
            creator_id,
            metadata,
            embedding,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn creator_roundtrip() {
        let mut creator = CreatorEntity::new(EntityId::new(99));
        creator
            .metadata
            .insert("name".to_string(), "bob".to_string());

        let bytes = creator.serialize();
        let restored = CreatorEntity::deserialize(EntityId::new(99), &bytes);

        assert_eq!(restored.creator_id, EntityId::new(99));
        assert_eq!(restored.metadata.get("name").unwrap(), "bob");
        assert!(restored.embedding.is_none());
    }
}
