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

//! Pool token DTO.

/// Application-facing normalized pool token DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PoolTokenDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related pool id.
    pub pool_id: i64,
    /// Related token id.
    pub token_id: i64,
    /// Token role.
    pub role: crate::PoolTokenRole,
    /// Optional vault address.
    pub vault_address: std::option::Option<std::string::String>,
    /// Optional token order inside the pool.
    pub token_order: std::option::Option<i64>,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Update timestamp.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl PoolTokenDto {
    /// Creates a new pool token DTO.
    pub fn new(
        pool_id: i64,
        token_id: i64,
        role: crate::PoolTokenRole,
        vault_address: std::option::Option<std::string::String>,
        token_order: std::option::Option<i64>,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            pool_id,
            token_id,
            role,
            vault_address,
            token_order,
            created_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::PoolTokenEntity> for PoolTokenDto {
    type Error = crate::Error;

    fn try_from(entity: crate::PoolTokenEntity) -> Result<Self, Self::Error> {
        let role_result = crate::PoolTokenRole::from_i16(entity.role);
        let role = match role_result {
            Ok(role) => role,
            Err(error) => return Err(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 pool_token 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 pool_token updated_at '{}': {}",
                    entity.updated_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            pool_id: entity.pool_id,
            token_id: entity.token_id,
            role,
            vault_address: entity.vault_address,
            token_order: entity.token_order,
            created_at,
            updated_at,
        });
    }
}
