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

//! Fee event DTO.

/// Application-facing normalized fee event DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FeeEventDto {
    /// 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>,
    /// Wallet or authority associated with the fee event, when decoded.
    pub actor_wallet: std::option::Option<std::string::String>,
    /// Token mint used to pay or collect the fee, when decoded.
    pub fee_token_mint: std::option::Option<std::string::String>,
    /// Raw fee amount as decimal text, when decoded.
    pub fee_amount_raw: 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 FeeEventDto {
    /// Creates a new fee 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>,
        actor_wallet: std::option::Option<std::string::String>,
        fee_token_mint: std::option::Option<std::string::String>,
        fee_amount_raw: 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,
            actor_wallet,
            fee_token_mint,
            fee_amount_raw,
            payload_json,
            executed_at: now,
            created_at: now,
        };
    }
}

impl TryFrom<crate::FeeEventEntity> for FeeEventDto {
    type Error = crate::Error;

    fn try_from(entity: crate::FeeEventEntity) -> 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 fee 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 fee 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 fee 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,
            actor_wallet: entity.actor_wallet,
            fee_token_mint: entity.fee_token_mint,
            fee_amount_raw: entity.fee_amount_raw,
            payload_json: entity.payload_json,
            executed_at,
            created_at,
        });
    }
}
