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

//! Queries for `k_sol_onchain_observations`.

/// Inserts one on-chain observation row and returns its numeric id.
pub async fn query_onchain_observations_insert(
    database: &crate::Database,
    dto: &crate::OnchainObservationDto,
) -> 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 on-chain observation payload: {}",
                error
            )));
        },
    };
    let slot_i64 = match dto.slot {
        Some(slot) => {
            let slot_result = i64::try_from(slot);
            match slot_result {
                Ok(slot) => Some(slot),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot convert on-chain observation slot '{}' to i64: {}",
                        slot, error
                    )));
                },
            }
        },
        None => None,
    };
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_onchain_observations (
    observation_kind,
    source_kind,
    endpoint_name,
    object_key,
    slot,
    payload_json,
    observed_at
)
VALUES (?, ?, ?, ?, ?, ?, ?)
                "#,
            )
            .bind(dto.observation_kind.clone())
            .bind(dto.source_kind.to_i16())
            .bind(dto.endpoint_name.clone())
            .bind(dto.object_key.clone())
            .bind(slot_i64)
            .bind(payload_json)
            .bind(dto.observed_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_onchain_observations on sqlite: {}",
                        error
                    )));
                },
            };
            return Ok(query_result.last_insert_rowid());
        },
    }
}

/// Lists recent on-chain observations ordered from newest to oldest.
pub async fn query_onchain_observations_list_recent(
    database: &crate::Database,
    limit: u32,
) -> Result<std::vec::Vec<crate::OnchainObservationDto>, 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::OnchainObservationEntity>(
                r#"
SELECT
    id,
    observation_kind,
    source_kind,
    endpoint_name,
    object_key,
    slot,
    payload_json,
    observed_at
FROM k_sol_onchain_observations
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 on-chain observations on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::OnchainObservationDto::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 onchain_observation_roundtrip_works() {
        let tempdir = tempfile::tempdir().expect("tempdir must succeed");
        let database_path = tempdir.path().join("onchain_observation.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::OnchainObservationDto::new(
            "token_discovered".to_string(),
            crate::ObservationSourceKind::WsRpc,
            Some("mainnet_public_ws_slots".to_string()),
            crate::WSOL_MINT_ID.to_string(),
            Some(123456u64),
            serde_json::json!({
                "mint": crate::WSOL_MINT_ID,
                "source": "ws"
            }),
        );
        let inserted_id = crate::query_onchain_observations_insert(&database, &dto)
            .await
            .expect("insert must succeed");
        assert!(inserted_id > 0);
        let listed = crate::query_onchain_observations_list_recent(&database, 10)
            .await
            .expect("list must succeed");
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].observation_kind, "token_discovered");
        assert_eq!(listed[0].source_kind, crate::ObservationSourceKind::WsRpc);
        assert_eq!(listed[0].slot, Some(123456u64));
    }
}
