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

//! Instruction observation DTOs.

/// Persisted technical observation for one Solana instruction.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InstructionObservationDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Stable observation key.
    pub observation_key: std::string::String,
    /// Parent transaction id.
    pub transaction_id: i64,
    /// Parent transaction signature.
    pub signature: std::string::String,
    /// Optional Solana slot.
    pub slot: std::option::Option<i64>,
    /// Optional block time.
    pub block_time: std::option::Option<i64>,
    /// Whether the parent transaction failed.
    pub failed: bool,
    /// Instruction row id.
    pub instruction_id: i64,
    /// Optional parent instruction id.
    pub parent_instruction_id: std::option::Option<i64>,
    /// Outer instruction index.
    pub instruction_index: i64,
    /// Optional inner instruction index.
    pub inner_instruction_index: std::option::Option<i64>,
    /// Instruction program id.
    pub program_id: std::string::String,
    /// Local decoder code when resolved.
    pub decoder_code: std::option::Option<std::string::String>,
    /// Instruction discriminator bytes as lower-hex; AMM v4 uses one byte, Anchor-style programs use eight bytes.
    pub discriminator_hex: std::option::Option<std::string::String>,
    /// Known local instruction name when resolved.
    pub instruction_name: std::option::Option<std::string::String>,
    /// Serialized accounts JSON.
    pub accounts_json: std::string::String,
    /// Optional serialized data JSON.
    pub data_json: std::option::Option<std::string::String>,
    /// Optional decoded pool account from local decoded events.
    pub pool_account: std::option::Option<std::string::String>,
    /// Optional decoded event kind attached to this instruction.
    pub decoded_event_kind: std::option::Option<std::string::String>,
    /// Optional decoded event id attached to this instruction.
    pub decoded_event_id: std::option::Option<i64>,
    /// First observation timestamp.
    pub observed_at: chrono::DateTime<chrono::Utc>,
    /// Last refresh timestamp.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Raw source row used to rebuild the technical instruction-observation index.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct InstructionObservationSourceRow {
    /// Internal transaction id.
    pub transaction_id: i64,
    /// Transaction signature.
    pub signature: std::string::String,
    /// Optional slot number.
    pub slot: std::option::Option<i64>,
    /// Optional block time.
    pub block_time: std::option::Option<i64>,
    /// Optional transaction error JSON.
    pub err_json: std::option::Option<std::string::String>,
    /// Internal instruction id.
    pub instruction_id: i64,
    /// Optional parent instruction id for CPI rows.
    pub parent_instruction_id: std::option::Option<i64>,
    /// Outer instruction index.
    pub instruction_index: i64,
    /// Optional inner instruction index.
    pub inner_instruction_index: std::option::Option<i64>,
    /// Program id, when available.
    pub program_id: std::option::Option<std::string::String>,
    /// Instruction account list JSON.
    pub accounts_json: std::string::String,
    /// Optional instruction data JSON.
    pub data_json: std::option::Option<std::string::String>,
    /// Optional pool account resolved from a decoded event on the same instruction.
    pub pool_account: std::option::Option<std::string::String>,
    /// Optional decoded event kind on the same instruction.
    pub decoded_event_kind: std::option::Option<std::string::String>,
    /// Optional decoded event id on the same instruction.
    pub decoded_event_id: std::option::Option<i64>,
}

impl InstructionObservationDto {
    /// Creates a new instruction observation DTO.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        observation_key: std::string::String,
        transaction_id: i64,
        signature: std::string::String,
        slot: std::option::Option<i64>,
        block_time: std::option::Option<i64>,
        failed: bool,
        instruction_id: i64,
        parent_instruction_id: std::option::Option<i64>,
        instruction_index: i64,
        inner_instruction_index: std::option::Option<i64>,
        program_id: std::string::String,
        decoder_code: std::option::Option<std::string::String>,
        discriminator_hex: std::option::Option<std::string::String>,
        instruction_name: std::option::Option<std::string::String>,
        accounts_json: std::string::String,
        data_json: std::option::Option<std::string::String>,
        pool_account: std::option::Option<std::string::String>,
        decoded_event_kind: std::option::Option<std::string::String>,
        decoded_event_id: std::option::Option<i64>,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            observation_key,
            transaction_id,
            signature,
            slot,
            block_time,
            failed,
            instruction_id,
            parent_instruction_id,
            instruction_index,
            inner_instruction_index,
            program_id,
            decoder_code,
            discriminator_hex,
            instruction_name,
            accounts_json,
            data_json,
            pool_account,
            decoded_event_kind,
            decoded_event_id,
            observed_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::InstructionObservationEntity> for InstructionObservationDto {
    type Error = crate::Error;

    fn try_from(entity: crate::InstructionObservationEntity) -> Result<Self, Self::Error> {
        let observed_at_result = chrono::DateTime::parse_from_rfc3339(entity.observed_at.as_str());
        let observed_at = match observed_at_result {
            Ok(observed_at) => observed_at.with_timezone(&chrono::Utc),
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse instruction observation observed_at '{}': {}",
                    entity.observed_at, error
                )));
            },
        };
        let updated_at_result = chrono::DateTime::parse_from_rfc3339(entity.updated_at.as_str());
        let updated_at = match updated_at_result {
            Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse instruction observation updated_at '{}': {}",
                    entity.updated_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            observation_key: entity.observation_key,
            transaction_id: entity.transaction_id,
            signature: entity.signature,
            slot: entity.slot,
            block_time: entity.block_time,
            failed: entity.failed != 0,
            instruction_id: entity.instruction_id,
            parent_instruction_id: entity.parent_instruction_id,
            instruction_index: entity.instruction_index,
            inner_instruction_index: entity.inner_instruction_index,
            program_id: entity.program_id,
            decoder_code: entity.decoder_code,
            discriminator_hex: entity.discriminator_hex,
            instruction_name: entity.instruction_name,
            accounts_json: entity.accounts_json,
            data_json: entity.data_json,
            pool_account: entity.pool_account,
            decoded_event_kind: entity.decoded_event_kind,
            decoded_event_id: entity.decoded_event_id,
            observed_at,
            updated_at,
        });
    }
}
