// file: kb_lib/src/db/queries/analysis_signal.rs

//! Queries for `k_sol_analysis_signals`.

/// Inserts one analysis signal row and returns its numeric id.
pub async fn query_analysis_signals_insert(
    database: &crate::Database,
    dto: &crate::AnalysisSignalDto,
) -> Result<i64, crate::Error> {
    let payload_json_result = serde_json::to_string(&dto.payload);
    let payload_json = match payload_json_result {
        Ok(payload_json) => payload_json,
        Err(error) => {
            return Err(crate::Error::Db(format!(
                "cannot serialize analysis signal payload: {}",
                error
            )));
        },
    };
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_analysis_signals (
    signal_kind,
    severity,
    object_key,
    related_observation_id,
    score,
    payload_json,
    created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?)
                "#,
            )
            .bind(dto.signal_kind.clone())
            .bind(dto.severity.to_i16())
            .bind(dto.object_key.clone())
            .bind(dto.related_observation_id)
            .bind(dto.score)
            .bind(payload_json)
            .bind(dto.created_at.to_rfc3339())
            .execute(pool)
            .await;
            let query_result = match query_result {
                Ok(query_result) => query_result,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot insert k_sol_analysis_signals on sqlite: {}",
                        error
                    )));
                },
            };
            return Ok(query_result.last_insert_rowid());
        },
    }
}

/// Lists recent analysis signals ordered from newest to oldest.
pub async fn query_analysis_signals_list(
    database: &crate::Database,
    limit: u32,
) -> Result<std::vec::Vec<crate::AnalysisSignalDto>, crate::Error> {
    if limit == 0 {
        return Ok(std::vec::Vec::new());
    }
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::AnalysisSignalEntity>(
                r#"
SELECT
    id,
    signal_kind,
    severity,
    object_key,
    related_observation_id,
    score,
    payload_json,
    created_at
FROM k_sol_analysis_signals
ORDER BY id DESC
LIMIT ?
                    "#,
            )
            .bind(i64::from(limit))
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list analysis signals on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::AnalysisSignalDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn analysis_signal_roundtrip_works() {
        let tempdir = tempfile::tempdir().expect("tempdir must succeed");
        let database_path = tempdir.path().join("analysis_signal.sqlite3");
        let config = crate::DatabaseConfig {
            enabled: true,
            backend: crate::DatabaseBackend::Sqlite,
            sqlite: crate::SqliteDatabaseConfig {
                path: database_path.to_string_lossy().to_string(),
                create_if_missing: true,
                busy_timeout_ms: 5000,
                max_connections: 1,
                auto_initialize_schema: true,
                use_wal: true,
            },
        };
        let database = crate::Database::connect_and_initialize(&config)
            .await
            .expect("database init must succeed");
        let dto = crate::AnalysisSignalDto::new(
            "candidate_token".to_string(),
            crate::AnalysisSignalSeverity::Medium,
            crate::WSOL_MINT_ID.to_string(),
            None,
            Some(0.72),
            serde_json::json!({
                "reason": "fresh_token_with_activity"
            }),
        );
        let inserted_id = crate::query_analysis_signals_insert(&database, &dto)
            .await
            .expect("insert must succeed");
        assert!(inserted_id > 0);
        let listed = crate::query_analysis_signals_list(&database, 10)
            .await
            .expect("list must succeed");
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].signal_kind, "candidate_token");
        assert_eq!(listed[0].severity, crate::AnalysisSignalSeverity::Medium);
        assert_eq!(listed[0].score, Some(0.72));
    }
}
