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

//! Queries for `k_sol_transaction_classifications`.

/// Inserts or updates one transaction classification row.
pub async fn query_transaction_classifications_upsert(
    database: &crate::Database,
    dto: &crate::TransactionClassificationDto,
) -> Result<i64, crate::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 transaction classification slot '{}' to i64: {}",
                        slot, error
                    )));
                },
            }
        },
        None => None,
    };
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_transaction_classifications (
    transaction_id,
    signature,
    slot,
    classification_kind,
    primary_protocol,
    primary_program_id,
    confidence_level,
    reason,
    evidence_json,
    created_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(transaction_id) DO UPDATE SET
    signature = excluded.signature,
    slot = excluded.slot,
    classification_kind = excluded.classification_kind,
    primary_protocol = excluded.primary_protocol,
    primary_program_id = excluded.primary_program_id,
    confidence_level = excluded.confidence_level,
    reason = excluded.reason,
    evidence_json = excluded.evidence_json,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.transaction_id)
            .bind(dto.signature.clone())
            .bind(slot_i64)
            .bind(dto.classification_kind.clone())
            .bind(dto.primary_protocol.clone())
            .bind(dto.primary_program_id.clone())
            .bind(i64::from(dto.confidence_level))
            .bind(dto.reason.clone())
            .bind(dto.evidence_json.clone())
            .bind(dto.created_at.to_rfc3339())
            .bind(dto.updated_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = query_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_transaction_classifications on sqlite: {}",
                    error
                )));
            }

            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_transaction_classifications
WHERE transaction_id = ?
LIMIT 1
                "#,
            )
            .bind(dto.transaction_id)
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_transaction_classifications id for transaction_id '{}' on sqlite: {}",
                        dto.transaction_id, error
                    )));
                },
            }
        },
    }
}

/// Reads one transaction classification by transaction id.
pub async fn query_transaction_classifications_get_by_transaction_id(
    database: &crate::Database,
    transaction_id: i64,
) -> Result<std::option::Option<crate::TransactionClassificationDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result =
                sqlx::query_as::<sqlx::Sqlite, crate::TransactionClassificationEntity>(
                    r#"
SELECT
    id,
    transaction_id,
    signature,
    slot,
    classification_kind,
    primary_protocol,
    primary_program_id,
    confidence_level,
    reason,
    evidence_json,
    created_at,
    updated_at
FROM k_sol_transaction_classifications
WHERE transaction_id = ?
LIMIT 1
                    "#,
                )
                .bind(transaction_id)
                .fetch_optional(pool)
                .await;
            let entity_option = match query_result {
                Ok(entity_option) => entity_option,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_transaction_classifications for transaction_id '{}' on sqlite: {}",
                        transaction_id, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::TransactionClassificationDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Reads one transaction classification by signature.
pub async fn query_transaction_classifications_get_by_signature(
    database: &crate::Database,
    signature: &str,
) -> Result<std::option::Option<crate::TransactionClassificationDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result =
                sqlx::query_as::<sqlx::Sqlite, crate::TransactionClassificationEntity>(
                    r#"
SELECT
    id,
    transaction_id,
    signature,
    slot,
    classification_kind,
    primary_protocol,
    primary_program_id,
    confidence_level,
    reason,
    evidence_json,
    created_at,
    updated_at
FROM k_sol_transaction_classifications
WHERE signature = ?
LIMIT 1
                    "#,
                )
                .bind(signature.to_string())
                .fetch_optional(pool)
                .await;
            let entity_option = match query_result {
                Ok(entity_option) => entity_option,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_transaction_classifications for signature '{}' on sqlite: {}",
                        signature, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::TransactionClassificationDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Lists recent transaction classifications ordered from newest to oldest.
pub async fn query_transaction_classifications_list_recent(
    database: &crate::Database,
    limit: u32,
) -> Result<std::vec::Vec<crate::TransactionClassificationDto>, 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::TransactionClassificationEntity>(
                    r#"
SELECT
    id,
    transaction_id,
    signature,
    slot,
    classification_kind,
    primary_protocol,
    primary_program_id,
    confidence_level,
    reason,
    evidence_json,
    created_at,
    updated_at
FROM k_sol_transaction_classifications
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 k_sol_transaction_classifications on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::TransactionClassificationDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };

                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
