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

//! DEX DTO.

/// Application-facing normalized DEX DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DexDto {
    /// 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 primary program id.
    pub program_id: std::option::Option<std::string::String>,
    /// Optional router program id.
    pub router_program_id: std::option::Option<std::string::String>,
    /// Whether this DEX 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 DexDto {
    /// Creates a new DEX DTO.
    pub fn new(
        code: std::string::String,
        name: std::string::String,
        program_id: std::option::Option<std::string::String>,
        router_program_id: std::option::Option<std::string::String>,
        is_enabled: bool,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            code,
            name,
            program_id,
            router_program_id,
            is_enabled,
            created_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::DexEntity> for DexDto {
    type Error = crate::Error;

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