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

//! Queries for `k_sol_swaps`.

/// Inserts or updates one normalized swap row.
pub async fn query_swaps_upsert(
    database: &crate::Database,
    dto: &crate::SwapDto,
) -> 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 swap slot '{}' to i64: {}",
                        slot, error
                    )));
                },
            }
        },
        None => None,
    };
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_swaps (
    dex_id,
    pool_id,
    pair_id,
    signature,
    instruction_index,
    slot,
    trader_wallet,
    base_token_id,
    quote_token_id,
    base_amount,
    quote_amount,
    price_quote,
    trade_side,
    executed_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(signature, instruction_index) DO UPDATE SET
    dex_id = excluded.dex_id,
    pool_id = excluded.pool_id,
    pair_id = excluded.pair_id,
    slot = excluded.slot,
    trader_wallet = excluded.trader_wallet,
    base_token_id = excluded.base_token_id,
    quote_token_id = excluded.quote_token_id,
    base_amount = excluded.base_amount,
    quote_amount = excluded.quote_amount,
    price_quote = excluded.price_quote,
    trade_side = excluded.trade_side,
    executed_at = excluded.executed_at
                "#,
            )
            .bind(dto.dex_id)
            .bind(dto.pool_id)
            .bind(dto.pair_id)
            .bind(dto.signature.clone())
            .bind(dto.instruction_index)
            .bind(slot_i64)
            .bind(dto.trader_wallet.clone())
            .bind(dto.base_token_id)
            .bind(dto.quote_token_id)
            .bind(dto.base_amount.clone())
            .bind(dto.quote_amount.clone())
            .bind(dto.price_quote.clone())
            .bind(dto.trade_side.to_i16())
            .bind(dto.executed_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = query_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_swaps on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_swaps
WHERE signature = ? AND instruction_index = ?
LIMIT 1
                "#,
            )
            .bind(dto.signature.clone())
            .bind(dto.instruction_index)
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_swaps id for signature '{}' and instruction_index '{}' on sqlite: {}",
                        dto.signature, dto.instruction_index, error
                    )));
                },
            }
        },
    }
}

/// Lists recent swaps ordered from newest to oldest.
pub async fn query_swaps_list_recent(
    database: &crate::Database,
    limit: u32,
) -> Result<std::vec::Vec<crate::SwapDto>, 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::SwapEntity>(
                r#"
SELECT
    id,
    dex_id,
    pool_id,
    pair_id,
    signature,
    instruction_index,
    slot,
    trader_wallet,
    base_token_id,
    quote_token_id,
    base_amount,
    quote_amount,
    price_quote,
    trade_side,
    executed_at
FROM k_sol_swaps
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_swaps on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::SwapDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
