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

//! Normalized pool DTO.

/// Application-facing normalized pool DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PoolDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related DEX id.
    pub dex_id: i64,
    /// Pool address.
    pub address: std::string::String,
    /// Pool kind.
    pub pool_kind: crate::PoolKind,
    /// Pool status.
    pub status: crate::PoolStatus,
    /// First seen timestamp.
    pub first_seen_at: chrono::DateTime<chrono::Utc>,
    /// Update timestamp.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl PoolDto {
    /// Creates a new pool DTO.
    pub fn new(
        dex_id: i64,
        address: std::string::String,
        pool_kind: crate::PoolKind,
        status: crate::PoolStatus,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            dex_id,
            address,
            pool_kind,
            status,
            first_seen_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::PoolEntity> for PoolDto {
    type Error = crate::Error;

    fn try_from(entity: crate::PoolEntity) -> Result<Self, Self::Error> {
        let pool_kind_result = crate::PoolKind::from_i16(entity.pool_kind);
        let pool_kind = match pool_kind_result {
            Ok(pool_kind) => pool_kind,
            Err(error) => return Err(error),
        };
        let status_result = crate::PoolStatus::from_i16(entity.status);
        let status = match status_result {
            Ok(status) => status,
            Err(error) => return Err(error),
        };
        let first_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.first_seen_at);
        let first_seen_at = match first_seen_at_result {
            Ok(first_seen_at) => first_seen_at.with_timezone(&chrono::Utc),
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse pool first_seen_at '{}': {}",
                    entity.first_seen_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 pool updated_at '{}': {}",
                    entity.updated_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            dex_id: entity.dex_id,
            address: entity.address,
            pool_kind,
            status,
            first_seen_at,
            updated_at,
        });
    }
}
