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

//! Token account event DTO.

/// Application-facing normalized token-account event DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenAccountEventDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related transaction id.
    pub transaction_id: std::option::Option<i64>,
    /// Related decoded event id.
    pub decoded_event_id: std::option::Option<i64>,
    /// Related DEX id.
    pub dex_id: std::option::Option<i64>,
    /// Related pool id, when known.
    pub pool_id: std::option::Option<i64>,
    /// Related pair id, when known.
    pub pair_id: std::option::Option<i64>,
    /// Transaction signature.
    pub signature: std::string::String,
    /// Instruction index inside the transaction.
    pub instruction_index: i64,
    /// Optional slot number.
    pub slot: std::option::Option<u64>,
    /// Protocol name.
    pub protocol_name: std::string::String,
    /// Program id.
    pub program_id: std::option::Option<std::string::String>,
    /// Event kind.
    pub event_kind: std::string::String,
    /// Token account, when known.
    pub token_account: std::option::Option<std::string::String>,
    /// Token mint, when known.
    pub token_mint: std::option::Option<std::string::String>,
    /// Owner wallet, when known.
    pub owner_wallet: std::option::Option<std::string::String>,
    /// Token-account action.
    pub account_action: std::option::Option<std::string::String>,
    /// Raw decoded payload.
    pub payload_json: std::option::Option<std::string::String>,
    /// Execution timestamp.
    pub executed_at: chrono::DateTime<chrono::Utc>,
}

impl TokenAccountEventDto {
    /// Creates a new token-account event DTO.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        transaction_id: std::option::Option<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,
        instruction_index: i64,
        slot: std::option::Option<u64>,
        protocol_name: std::string::String,
        program_id: std::option::Option<std::string::String>,
        event_kind: std::string::String,
        token_account: std::option::Option<std::string::String>,
        token_mint: std::option::Option<std::string::String>,
        owner_wallet: std::option::Option<std::string::String>,
        account_action: std::option::Option<std::string::String>,
        payload_json: std::option::Option<std::string::String>,
    ) -> Self {
        return Self {
            id: None,
            transaction_id,
            decoded_event_id,
            dex_id,
            pool_id,
            pair_id,
            signature,
            instruction_index,
            slot,
            protocol_name,
            program_id,
            event_kind,
            token_account,
            token_mint,
            owner_wallet,
            account_action,
            payload_json,
            executed_at: chrono::Utc::now(),
        };
    }
}

impl TryFrom<crate::TokenAccountEventEntity> for TokenAccountEventDto {
    type Error = crate::Error;

    fn try_from(entity: crate::TokenAccountEventEntity) -> 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 token account event executed_at '{}': {}",
                    entity.executed_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 token account 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,
            instruction_index: entity.instruction_index,
            slot,
            protocol_name: entity.protocol_name,
            program_id: entity.program_id,
            event_kind: entity.event_kind,
            token_account: entity.token_account,
            token_mint: entity.token_mint,
            owner_wallet: entity.owner_wallet,
            account_action: entity.account_action,
            payload_json: entity.payload_json,
            executed_at,
        });
    }
}
