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

//! Orderbook event DTO.

/// Application-facing normalized orderbook or limit-order event DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OrderbookEventDto {
    /// 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,
    /// Normalized orderbook action.
    pub order_action: std::string::String,
    /// Pool account address, when decoded.
    pub pool_account: std::option::Option<std::string::String>,
    /// Market/orderbook account, when decoded.
    pub market_account: std::option::Option<std::string::String>,
    /// Wallet or authority associated with the event, when decoded.
    pub actor_wallet: std::option::Option<std::string::String>,
    /// Limit/order account, when decoded.
    pub order_account: std::option::Option<std::string::String>,
    /// Base or token A mint, when decoded.
    pub base_token_mint: std::option::Option<std::string::String>,
    /// Quote or token B mint, when decoded.
    pub quote_token_mint: std::option::Option<std::string::String>,
    /// Raw order amount as decimal text, when decoded.
    pub amount_raw: std::option::Option<std::string::String>,
    /// Raw minimum amount as decimal text, when decoded.
    pub amount_min_raw: std::option::Option<std::string::String>,
    /// Optional tick index for CLMM limit orders.
    pub tick_index: std::option::Option<i64>,
    /// Optional zero-for-one side flag.
    pub zero_for_one: std::option::Option<bool>,
    /// 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 OrderbookEventDto {
    /// Creates a new orderbook 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,
        order_action: std::string::String,
        pool_account: std::option::Option<std::string::String>,
        market_account: std::option::Option<std::string::String>,
        actor_wallet: std::option::Option<std::string::String>,
        order_account: std::option::Option<std::string::String>,
        base_token_mint: std::option::Option<std::string::String>,
        quote_token_mint: std::option::Option<std::string::String>,
        amount_raw: std::option::Option<std::string::String>,
        amount_min_raw: std::option::Option<std::string::String>,
        tick_index: std::option::Option<i64>,
        zero_for_one: std::option::Option<bool>,
        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,
            order_action,
            pool_account,
            market_account,
            actor_wallet,
            order_account,
            base_token_mint,
            quote_token_mint,
            amount_raw,
            amount_min_raw,
            tick_index,
            zero_for_one,
            payload_json,
            executed_at: now,
            created_at: now,
        };
    }
}

impl TryFrom<crate::OrderbookEventEntity> for OrderbookEventDto {
    type Error = crate::Error;

    fn try_from(entity: crate::OrderbookEventEntity) -> 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 orderbook 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 orderbook 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 orderbook event slot '{}' to u64: {}",
                            slot, error
                        )));
                    },
                }
            },
            None => None,
        };
        let zero_for_one = match entity.zero_for_one {
            Some(0) => Some(false),
            Some(_) => Some(true),
            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,
            order_action: entity.order_action,
            pool_account: entity.pool_account,
            market_account: entity.market_account,
            actor_wallet: entity.actor_wallet,
            order_account: entity.order_account,
            base_token_mint: entity.base_token_mint,
            quote_token_mint: entity.quote_token_mint,
            amount_raw: entity.amount_raw,
            amount_min_raw: entity.amount_min_raw,
            tick_index: entity.tick_index,
            zero_for_one,
            payload_json: entity.payload_json,
            executed_at,
            created_at,
        });
    }
}
