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

//! Launch surface key DTO.

/// Application-facing launch surface key DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LaunchSurfaceKeyDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related launch surface id.
    pub launch_surface_id: i64,
    /// Stable key kind.
    pub match_kind: std::string::String,
    /// Stable key value.
    pub match_value: std::string::String,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Update timestamp.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl LaunchSurfaceKeyDto {
    /// Creates a new launch surface key DTO.
    pub fn new(
        launch_surface_id: i64,
        match_kind: std::string::String,
        match_value: std::string::String,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            launch_surface_id,
            match_kind,
            match_value,
            created_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::LaunchSurfaceKeyEntity> for LaunchSurfaceKeyDto {
    type Error = crate::Error;

    fn try_from(entity: crate::LaunchSurfaceKeyEntity) -> 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 launch_surface_key created_at '{}': {}",
                    entity.created_at, error
                )));
            },
        };
        let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
        let updated_at = match updated_at_result {
            Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse launch_surface_key updated_at '{}': {}",
                    entity.updated_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            launch_surface_id: entity.launch_surface_id,
            match_kind: entity.match_kind,
            match_value: entity.match_value,
            created_at,
            updated_at,
        });
    }
}
