// file: kb_lib/src/db/dtos/db_runtime_event.rs

//! Runtime event DTO.

/// Application-facing runtime event DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DbRuntimeEventDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Event kind.
    pub event_kind: std::string::String,
    /// Severity level.
    pub level: crate::DbRuntimeEventLevel,
    /// Event source.
    pub source: std::string::String,
    /// Human-readable message.
    pub message: std::string::String,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl DbRuntimeEventDto {
    /// Creates a new runtime event DTO with the current creation timestamp.
    pub fn new(
        event_kind: std::string::String,
        level: crate::DbRuntimeEventLevel,
        source: std::string::String,
        message: std::string::String,
    ) -> Self {
        return Self {
            id: None,
            event_kind,
            level,
            source,
            message,
            created_at: chrono::Utc::now(),
        };
    }
}

impl TryFrom<crate::DbRuntimeEventEntity> for DbRuntimeEventDto {
    type Error = crate::Error;

    fn try_from(entity: crate::DbRuntimeEventEntity) -> Result<Self, Self::Error> {
        let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
        let created_at = match created_at_result {
            Ok(created_at) => created_at.with_timezone(&chrono::Utc),
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse runtime event created_at '{}': {}",
                    entity.created_at, error
                )));
            },
        };
        let level_result = crate::DbRuntimeEventLevel::from_i16(entity.level);
        let level = match level_result {
            Ok(level) => level,
            Err(error) => return Err(error),
        };
        return Ok(Self {
            id: Some(entity.id),
            event_kind: entity.event_kind,
            level,
            source: entity.source,
            message: entity.message,
            created_at,
        });
    }
}
