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

//! Pool lifecycle event DTO.

/// Application-facing normalized pool lifecycle event DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PoolLifecycleEventDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related transaction id.
    pub transaction_id: i64,
    /// Related decoded DEX event id, when available.
    pub decoded_event_id: std::option::Option<i64>,
    /// Related DEX id, when the DEX row is known.
    pub dex_id: std::option::Option<i64>,
    /// Related pool id, when the pool row is known.
    pub pool_id: std::option::Option<i64>,
    /// Related pair id, when the pair row is known.
    pub pair_id: std::option::Option<i64>,
    /// Transaction signature.
    pub signature: std::string::String,
    /// Optional slot number.
    pub slot: std::option::Option<u64>,
    /// Protocol name that emitted the decoded event.
    pub protocol_name: std::string::String,
    /// Program id that emitted the decoded event.
    pub program_id: std::string::String,
    /// Stable decoded event kind.
    pub event_kind: std::string::String,
    /// Pool account address, when decoded.
    pub pool_account: std::option::Option<std::string::String>,
    /// First token mint, when decoded.
    pub token_a_mint: std::option::Option<std::string::String>,
    /// Second token mint, when decoded.
    pub token_b_mint: std::option::Option<std::string::String>,
    /// Source decoded payload JSON.
    pub payload_json: std::string::String,
    /// Execution timestamp.
    pub executed_at: chrono::DateTime<chrono::Utc>,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl PoolLifecycleEventDto {
    /// Creates a new pool lifecycle event DTO.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        transaction_id: i64,
        decoded_event_id: std::option::Option<i64>,
        dex_id: std::option::Option<i64>,
        pool_id: std::option::Option<i64>,
        pair_id: std::option::Option<i64>,
        signature: std::string::String,
        slot: std::option::Option<u64>,
        protocol_name: std::string::String,
        program_id: std::string::String,
        event_kind: std::string::String,
        pool_account: std::option::Option<std::string::String>,
        token_a_mint: std::option::Option<std::string::String>,
        token_b_mint: std::option::Option<std::string::String>,
        payload_json: std::string::String,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            transaction_id,
            decoded_event_id,
            dex_id,
            pool_id,
            pair_id,
            signature,
            slot,
            protocol_name,
            program_id,
            event_kind,
            pool_account,
            token_a_mint,
            token_b_mint,
            payload_json,
            executed_at: now,
            created_at: now,
        };
    }
}

impl TryFrom<crate::PoolLifecycleEventEntity> for PoolLifecycleEventDto {
    type Error = crate::Error;

    fn try_from(entity: crate::PoolLifecycleEventEntity) -> Result<Self, Self::Error> {
        let executed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.executed_at);
        let executed_at = match executed_at_result {
            Ok(executed_at) => executed_at.with_timezone(&chrono::Utc),
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse pool lifecycle event executed_at '{}': {}",
                    entity.executed_at, 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 lifecycle event created_at '{}': {}",
                    entity.created_at, error
                )));
            },
        };
        let slot = match entity.slot {
            Some(slot) => {
                let slot_result = u64::try_from(slot);
                match slot_result {
                    Ok(slot) => Some(slot),
                    Err(error) => {
                        return Err(crate::Error::Db(format!(
                            "cannot convert pool lifecycle event slot '{}' to u64: {}",
                            slot, error
                        )));
                    },
                }
            },
            None => None,
        };
        return Ok(Self {
            id: Some(entity.id),
            transaction_id: entity.transaction_id,
            decoded_event_id: entity.decoded_event_id,
            dex_id: entity.dex_id,
            pool_id: entity.pool_id,
            pair_id: entity.pair_id,
            signature: entity.signature,
            slot,
            protocol_name: entity.protocol_name,
            program_id: entity.program_id,
            event_kind: entity.event_kind,
            pool_account: entity.pool_account,
            token_a_mint: entity.token_a_mint,
            token_b_mint: entity.token_b_mint,
            payload_json: entity.payload_json,
            executed_at,
            created_at,
        });
    }
}
