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

//! Launch surface DTO.

/// Application-facing launch surface DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LaunchSurfaceDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Stable short code.
    pub code: std::string::String,
    /// Display name.
    pub name: std::string::String,
    /// Optional protocol family hint.
    pub protocol_family: std::option::Option<std::string::String>,
    /// Whether the surface is enabled.
    pub is_enabled: bool,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Update timestamp.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl LaunchSurfaceDto {
    /// Creates a new launch surface DTO.
    pub fn new(
        code: std::string::String,
        name: std::string::String,
        protocol_family: std::option::Option<std::string::String>,
        is_enabled: bool,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            code,
            name,
            protocol_family,
            is_enabled,
            created_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::LaunchSurfaceEntity> for LaunchSurfaceDto {
    type Error = crate::Error;

    fn try_from(entity: crate::LaunchSurfaceEntity) -> 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 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 updated_at '{}': {}",
                    entity.updated_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            code: entity.code,
            name: entity.name,
            protocol_family: entity.protocol_family,
            is_enabled: entity.is_enabled != 0,
            created_at,
            updated_at,
        });
    }
}
