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

//! Queries for `k_sol_wallets`.

/// Inserts or updates one wallet row and returns its stable internal id.
pub async fn query_wallets_upsert(
    database: &crate::Database,
    dto: &crate::WalletDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_wallets (
    address,
    label,
    first_seen_at,
    last_seen_at
)
VALUES (?, ?, ?, ?)
ON CONFLICT(address) DO UPDATE SET
    label = COALESCE(excluded.label, k_sol_wallets.label),
    last_seen_at = excluded.last_seen_at
                "#,
            )
            .bind(dto.address.clone())
            .bind(dto.label.clone())
            .bind(dto.first_seen_at.to_rfc3339())
            .bind(dto.last_seen_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = query_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_wallets on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_wallets
WHERE address = ?
LIMIT 1
                "#,
            )
            .bind(dto.address.clone())
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_wallets id for address '{}' on sqlite: {}",
                        dto.address, error
                    )));
                },
            }
        },
    }
}

/// Returns one wallet identified by its address, if it exists.
pub async fn query_wallets_get_by_address(
    database: &crate::Database,
    address: &str,
) -> Result<std::option::Option<crate::WalletDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::WalletEntity>(
                r#"
SELECT
    id,
    address,
    label,
    first_seen_at,
    last_seen_at
FROM k_sol_wallets
WHERE address = ?
LIMIT 1
                "#,
            )
            .bind(address)
            .fetch_optional(pool)
            .await;
            let entity_option = match query_result {
                Ok(entity_option) => entity_option,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot read k_sol_wallets '{}' on sqlite: {}",
                        address, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => return crate::WalletDto::try_from(entity).map(Some),
                None => return Ok(None),
            }
        },
    }
}

/// Lists all persisted wallets ordered by address.
pub async fn query_wallets_list(
    database: &crate::Database,
) -> Result<std::vec::Vec<crate::WalletDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::WalletEntity>(
                r#"
SELECT
    id,
    address,
    label,
    first_seen_at,
    last_seen_at
FROM k_sol_wallets
ORDER BY address ASC
                "#,
            )
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_wallets on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::WalletDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
