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

//! Swap DTO.

/// Application-facing normalized swap DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SwapDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related DEX id.
    pub dex_id: i64,
    /// Related pool id.
    pub pool_id: i64,
    /// Optional related pair id.
    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>,
    /// Optional trader wallet.
    pub trader_wallet: std::option::Option<std::string::String>,
    /// Base token id.
    pub base_token_id: i64,
    /// Quote token id.
    pub quote_token_id: i64,
    /// Base amount as decimal text.
    pub base_amount: std::string::String,
    /// Quote amount as decimal text.
    pub quote_amount: std::string::String,
    /// Optional price in quote units as decimal text.
    pub price_quote: std::option::Option<std::string::String>,
    /// Trade side relative to the base token.
    pub trade_side: crate::SwapTradeSide,
    /// Execution timestamp.
    pub executed_at: chrono::DateTime<chrono::Utc>,
}

impl SwapDto {
    /// Creates a new swap DTO.
    pub fn new(
        dex_id: i64,
        pool_id: i64,
        pair_id: std::option::Option<i64>,
        signature: std::string::String,
        instruction_index: i64,
        slot: std::option::Option<u64>,
        trader_wallet: std::option::Option<std::string::String>,
        base_token_id: i64,
        quote_token_id: i64,
        base_amount: std::string::String,
        quote_amount: std::string::String,
        price_quote: std::option::Option<std::string::String>,
        trade_side: crate::SwapTradeSide,
    ) -> Self {
        return Self {
            id: None,
            dex_id,
            pool_id,
            pair_id,
            signature,
            instruction_index,
            slot,
            trader_wallet,
            base_token_id,
            quote_token_id,
            base_amount,
            quote_amount,
            price_quote,
            trade_side,
            executed_at: chrono::Utc::now(),
        };
    }
}

impl TryFrom<crate::SwapEntity> for SwapDto {
    type Error = crate::Error;

    fn try_from(entity: crate::SwapEntity) -> Result<Self, Self::Error> {
        let trade_side_result = crate::SwapTradeSide::from_i16(entity.trade_side);
        let trade_side = match trade_side_result {
            Ok(trade_side) => trade_side,
            Err(error) => return Err(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 swap 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 swap slot '{}' to u64: {}",
                            slot, error
                        )));
                    },
                }
            },
            None => None,
        };
        return Ok(Self {
            id: Some(entity.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,
            trader_wallet: entity.trader_wallet,
            base_token_id: entity.base_token_id,
            quote_token_id: entity.quote_token_id,
            base_amount: entity.base_amount,
            quote_amount: entity.quote_amount,
            price_quote: entity.price_quote,
            trade_side,
            executed_at,
        });
    }
}
