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

//! Pair-analytic-signal DTO.

/// Application-facing pair-analytic-signal DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PairAnalyticSignalDto {
    /// Optional numeric primary key.
    pub id: std::option::Option<i64>,
    /// Related pair id.
    pub pair_id: i64,
    /// Stable signal kind.
    pub signal_kind: std::string::String,
    /// Signal severity.
    pub severity: crate::AnalysisSignalSeverity,
    /// Timeframe in seconds. Zero means non-bucketed signal.
    pub timeframe_seconds: i64,
    /// Inclusive bucket start in unix seconds. Zero means non-bucketed signal.
    pub bucket_start_unix: i64,
    /// Optional numeric score.
    pub score: std::option::Option<f64>,
    /// Signal value payload.
    pub signal_value: serde_json::Value,
    /// Optional first transaction id that produced this signal key.
    pub first_transaction_id: std::option::Option<i64>,
    /// Optional last transaction id that produced this signal key.
    pub last_transaction_id: std::option::Option<i64>,
    /// Creation timestamp.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Update timestamp.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl PairAnalyticSignalDto {
    /// Creates a new pair-analytic-signal DTO.
    pub fn new(
        pair_id: i64,
        signal_kind: std::string::String,
        severity: crate::AnalysisSignalSeverity,
        timeframe_seconds: i64,
        bucket_start_unix: i64,
        score: std::option::Option<f64>,
        signal_value: serde_json::Value,
        first_transaction_id: std::option::Option<i64>,
        last_transaction_id: std::option::Option<i64>,
    ) -> Self {
        let now = chrono::Utc::now();
        return Self {
            id: None,
            pair_id,
            signal_kind,
            severity,
            timeframe_seconds,
            bucket_start_unix,
            score,
            signal_value,
            first_transaction_id,
            last_transaction_id,
            created_at: now,
            updated_at: now,
        };
    }
}

impl TryFrom<crate::PairAnalyticSignalEntity> for PairAnalyticSignalDto {
    type Error = crate::Error;

    fn try_from(entity: crate::PairAnalyticSignalEntity) -> Result<Self, Self::Error> {
        let severity_result = crate::AnalysisSignalSeverity::from_i16(entity.severity);
        let severity = match severity_result {
            Ok(severity) => severity,
            Err(error) => return Err(error),
        };
        let signal_value_result =
            serde_json::from_str::<serde_json::Value>(entity.signal_value_json.as_str());
        let signal_value = match signal_value_result {
            Ok(signal_value) => signal_value,
            Err(error) => {
                return Err(crate::Error::Db(format!(
                    "cannot parse pair_analytic_signal signal_value_json '{}': {}",
                    entity.signal_value_json, error
                )));
            },
        };
        let created_at_result = chrono::DateTime::parse_from_rfc3339(entity.created_at.as_str());
        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 pair_analytic_signal created_at '{}': {}",
                    entity.created_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 pair_analytic_signal updated_at '{}': {}",
                    entity.updated_at, error
                )));
            },
        };
        return Ok(Self {
            id: Some(entity.id),
            pair_id: entity.pair_id,
            signal_kind: entity.signal_kind,
            severity,
            timeframe_seconds: entity.timeframe_seconds,
            bucket_start_unix: entity.bucket_start_unix,
            score: entity.score,
            signal_value,
            first_transaction_id: entity.first_transaction_id,
            last_transaction_id: entity.last_transaction_id,
            created_at,
            updated_at,
        });
    }
}
