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

//! Queries for `k_sol_wallet_participations`.

/// Inserts or updates one wallet-participation row and returns its stable internal id.
pub async fn query_wallet_participations_upsert(
    database: &crate::Database,
    dto: &crate::WalletParticipationDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_wallet_participations (
    wallet_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    role,
    unique_key,
    source_kind,
    source_endpoint_name,
    created_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(unique_key) DO UPDATE SET
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.wallet_id)
            .bind(dto.transaction_id)
            .bind(dto.decoded_event_id)
            .bind(dto.pool_id)
            .bind(dto.pair_id)
            .bind(dto.role.clone())
            .bind(dto.unique_key.clone())
            .bind(dto.source_kind.to_i16())
            .bind(dto.source_endpoint_name.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_wallet_participations on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_wallet_participations
WHERE unique_key = ?
LIMIT 1
                "#,
            )
            .bind(dto.unique_key.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_wallet_participations id for unique_key '{}' on sqlite: {}",
                        dto.unique_key, error
                    )));
                },
            }
        },
    }
}

/// Returns one wallet-participation identified by its unique key, if it exists.
pub async fn query_wallet_participations_get_by_unique_key(
    database: &crate::Database,
    unique_key: &str,
) -> Result<std::option::Option<crate::WalletParticipationDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::WalletParticipationEntity>(
                r#"
SELECT
    id,
    wallet_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    role,
    unique_key,
    source_kind,
    source_endpoint_name,
    created_at,
    updated_at
FROM k_sol_wallet_participations
WHERE unique_key = ?
LIMIT 1
                    "#,
            )
            .bind(unique_key)
            .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_wallet_participations by unique_key '{}' on sqlite: {}",
                        unique_key, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => return crate::WalletParticipationDto::try_from(entity).map(Some),
                None => return Ok(None),
            }
        },
    }
}

/// Lists wallet-participation rows for one wallet id.
pub async fn query_wallet_participations_list_by_wallet_id(
    database: &crate::Database,
    wallet_id: i64,
) -> Result<std::vec::Vec<crate::WalletParticipationDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::WalletParticipationEntity>(
                r#"
SELECT
    id,
    wallet_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    role,
    unique_key,
    source_kind,
    source_endpoint_name,
    created_at,
    updated_at
FROM k_sol_wallet_participations
WHERE wallet_id = ?
ORDER BY created_at ASC, id ASC
                    "#,
            )
            .bind(wallet_id)
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_wallet_participations by wallet_id '{}' on sqlite: {}",
                        wallet_id, error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::WalletParticipationDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}

/// Lists wallet-participation rows for one pool id.
pub async fn query_wallet_participations_list_by_pool_id(
    database: &crate::Database,
    pool_id: i64,
) -> Result<std::vec::Vec<crate::WalletParticipationDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::WalletParticipationEntity>(
                r#"
SELECT
    id,
    wallet_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    role,
    unique_key,
    source_kind,
    source_endpoint_name,
    created_at,
    updated_at
FROM k_sol_wallet_participations
WHERE pool_id = ?
ORDER BY created_at ASC, id ASC
                    "#,
            )
            .bind(pool_id)
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_wallet_participations by pool_id '{}' on sqlite: {}",
                        pool_id, error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::WalletParticipationDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
