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

//! Liquidity event DTO.

/// Application-facing normalized liquidity event DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LiquidityEventDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Optional related transaction id.
    pub transaction_id: std::option::Option<i64>,
    /// Optional related decoded DEX event id.
    pub decoded_event_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 program id that emitted the decoded event.
    pub program_id: std::option::Option<std::string::String>,
    /// Liquidity event kind.
    pub event_kind: crate::LiquidityEventKind,
    /// Optional original decoded event kind.
    pub event_kind_text: std::option::Option<std::string::String>,
    /// Optional actor wallet.
    pub actor_wallet: std::option::Option<std::string::String>,
    /// Base token id.
    pub base_token_id: i64,
    /// Quote token id.
    pub quote_token_id: i64,
    /// Optional LP token id.
    pub lp_token_id: std::option::Option<i64>,
    /// Base amount as decimal text.
    pub base_amount: std::string::String,
    /// Quote amount as decimal text.
    pub quote_amount: std::string::String,
    /// Optional LP amount as decimal text.
    pub lp_amount: std::option::Option<std::string::String>,
    /// Whether the persisted amount fields are complete.
    pub amounts_are_complete: bool,
    /// Optional source decoded payload JSON.
    pub payload_json: std::option::Option<std::string::String>,
    /// Execution timestamp.
    pub executed_at: chrono::DateTime<chrono::Utc>,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl LiquidityEventDto {
    /// Creates a new liquidity event 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>,
        event_kind: crate::LiquidityEventKind,
        actor_wallet: std::option::Option<std::string::String>,
        base_token_id: i64,
        quote_token_id: i64,
        lp_token_id: std::option::Option<i64>,
        base_amount: std::string::String,
        quote_amount: std::string::String,
        lp_amount: std::option::Option<std::string::String>,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            transaction_id: None,
            decoded_event_id: None,
            dex_id,
            pool_id,
            pair_id,
            signature,
            instruction_index,
            slot,
            program_id: None,
            event_kind,
            event_kind_text: None,
            actor_wallet,
            base_token_id,
            quote_token_id,
            lp_token_id,
            base_amount,
            quote_amount,
            lp_amount,
            amounts_are_complete: true,
            payload_json: None,
            executed_at: now,
            created_at: now,
        };
    }

    /// Adds decoded-event linkage and audit payload metadata to the DTO.
    #[allow(clippy::too_many_arguments)]
    pub fn with_decoded_event_metadata(
        mut self,
        transaction_id: std::option::Option<i64>,
        decoded_event_id: std::option::Option<i64>,
        program_id: std::option::Option<std::string::String>,
        event_kind_text: std::option::Option<std::string::String>,
        payload_json: std::option::Option<std::string::String>,
        amounts_are_complete: bool,
    ) -> Self {
        self.transaction_id = transaction_id;
        self.decoded_event_id = decoded_event_id;
        self.program_id = program_id;
        self.event_kind_text = event_kind_text;
        self.payload_json = payload_json;
        self.amounts_are_complete = amounts_are_complete;
        return self;
    }
}

impl TryFrom<crate::LiquidityEventEntity> for LiquidityEventDto {
    type Error = crate::Error;

    fn try_from(entity: crate::LiquidityEventEntity) -> Result<Self, Self::Error> {
        let event_kind_result = crate::LiquidityEventKind::from_i16(entity.event_kind);
        let event_kind = match event_kind_result {
            Ok(event_kind) => event_kind,
            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 liquidity 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 liquidity 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,
            program_id: entity.program_id,
            event_kind,
            event_kind_text: entity.event_kind_text,
            actor_wallet: entity.actor_wallet,
            base_token_id: entity.base_token_id,
            quote_token_id: entity.quote_token_id,
            lp_token_id: entity.lp_token_id,
            base_amount: entity.base_amount,
            quote_amount: entity.quote_amount,
            lp_amount: entity.lp_amount,
            amounts_are_complete: match entity.amounts_are_complete {
                Some(amounts_are_complete) => amounts_are_complete != 0,
                None => true,
            },
            payload_json: entity.payload_json,
            executed_at,
            created_at: match entity.created_at {
                Some(created_at) => {
                    let created_at_result = chrono::DateTime::parse_from_rfc3339(&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 liquidity event created_at '{}': {}",
                                created_at, error
                            )));
                        },
                    }
                },
                None => executed_at,
            },
        });
    }
}
