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

//! Protocol candidate DTO.

/// Application-facing protocol candidate DTO.
///
/// A protocol candidate records a program/instruction that should be inspected
/// later because it may correspond to an unsupported DEX, launch surface,
/// migration path or protocol-specific non-trade event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProtocolCandidateDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related chain transaction id.
    pub transaction_id: i64,
    /// Optional related chain instruction id.
    pub instruction_id: std::option::Option<i64>,
    /// Transaction signature.
    pub signature: std::string::String,
    /// Optional Solana slot.
    pub slot: std::option::Option<u64>,
    /// Program id observed in the transaction instruction.
    pub program_id: std::string::String,
    /// Optional program name hint from parsed transaction data.
    pub program_name_hint: std::option::Option<std::string::String>,
    /// Optional candidate protocol code.
    pub candidate_protocol: std::option::Option<std::string::String>,
    /// Optional candidate surface code.
    pub candidate_surface: std::option::Option<std::string::String>,
    /// Human-readable reason.
    pub reason: std::string::String,
    /// Serialized JSON evidence.
    pub evidence_json: std::string::String,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl ProtocolCandidateDto {
    /// Creates a protocol candidate DTO.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        transaction_id: i64,
        instruction_id: std::option::Option<i64>,
        signature: std::string::String,
        slot: std::option::Option<u64>,
        program_id: std::string::String,
        program_name_hint: std::option::Option<std::string::String>,
        candidate_protocol: std::option::Option<std::string::String>,
        candidate_surface: std::option::Option<std::string::String>,
        reason: std::string::String,
        evidence_json: std::string::String,
    ) -> Self {
        return Self {
            id: None,
            transaction_id,
            instruction_id,
            signature,
            slot,
            program_id,
            program_name_hint,
            candidate_protocol,
            candidate_surface,
            reason,
            evidence_json,
            created_at: chrono::Utc::now(),
        };
    }
}

impl TryFrom<crate::ProtocolCandidateEntity> for ProtocolCandidateDto {
    type Error = crate::Error;

    fn try_from(entity: crate::ProtocolCandidateEntity) -> Result<Self, Self::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 protocol candidate slot '{}' to u64: {}",
                            slot, error
                        )));
                    },
                }
            },
            None => None,
        };
        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 protocol candidate created_at '{}': {}",
                    entity.created_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            transaction_id: entity.transaction_id,
            instruction_id: entity.instruction_id,
            signature: entity.signature,
            slot,
            program_id: entity.program_id,
            program_name_hint: entity.program_name_hint,
            candidate_protocol: entity.candidate_protocol,
            candidate_surface: entity.candidate_surface,
            reason: entity.reason,
            evidence_json: entity.evidence_json,
            created_at,
        });
    }
}
