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

//! Queries for `k_sol_orderbook_events`.

/// Inserts or updates one normalized orderbook event row.
pub async fn query_orderbook_events_upsert(
    database: &crate::Database,
    dto: &crate::OrderbookEventDto,
) -> 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 orderbook event slot '{}' to i64: {}",
                        slot, error
                    )));
                },
            }
        },
        None => None,
    };
    let zero_for_one_i64 = match dto.zero_for_one {
        Some(true) => Some(1_i64),
        Some(false) => Some(0_i64),
        None => None,
    };
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let existing_id = match dto.decoded_event_id {
                Some(decoded_event_id) => {
                    let existing_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                        r#"
SELECT id
FROM k_sol_orderbook_events
WHERE decoded_event_id = ?
LIMIT 1
                        "#,
                    )
                    .bind(decoded_event_id)
                    .fetch_optional(pool)
                    .await;
                    match existing_result {
                        Ok(existing_id) => existing_id,
                        Err(error) => {
                            return Err(crate::Error::Db(format!(
                                "cannot fetch k_sol_orderbook_events id for decoded_event_id '{}' on sqlite: {}",
                                decoded_event_id, error
                            )));
                        },
                    }
                },
                None => None,
            };
            if let Some(id) = existing_id {
                let update_result = sqlx::query(
                    r#"
UPDATE k_sol_orderbook_events
SET
    transaction_id = ?,
    dex_id = ?,
    pool_id = ?,
    pair_id = ?,
    signature = ?,
    slot = ?,
    protocol_name = ?,
    program_id = ?,
    event_kind = ?,
    order_action = ?,
    pool_account = ?,
    market_account = ?,
    actor_wallet = ?,
    order_account = ?,
    base_token_mint = ?,
    quote_token_mint = ?,
    amount_raw = ?,
    amount_min_raw = ?,
    tick_index = ?,
    zero_for_one = ?,
    payload_json = ?,
    executed_at = ?
WHERE id = ?
                    "#,
                )
                .bind(dto.transaction_id)
                .bind(dto.dex_id)
                .bind(dto.pool_id)
                .bind(dto.pair_id)
                .bind(dto.signature.clone())
                .bind(slot_i64)
                .bind(dto.protocol_name.clone())
                .bind(dto.program_id.clone())
                .bind(dto.event_kind.clone())
                .bind(dto.order_action.clone())
                .bind(dto.pool_account.clone())
                .bind(dto.market_account.clone())
                .bind(dto.actor_wallet.clone())
                .bind(dto.order_account.clone())
                .bind(dto.base_token_mint.clone())
                .bind(dto.quote_token_mint.clone())
                .bind(dto.amount_raw.clone())
                .bind(dto.amount_min_raw.clone())
                .bind(dto.tick_index)
                .bind(zero_for_one_i64)
                .bind(dto.payload_json.clone())
                .bind(dto.executed_at.to_rfc3339())
                .bind(id)
                .execute(pool)
                .await;
                if let Err(error) = update_result {
                    return Err(crate::Error::Db(format!(
                        "cannot update k_sol_orderbook_events id '{}' on sqlite: {}",
                        id, error
                    )));
                }
                return Ok(id);
            }
            let insert_result = sqlx::query(
                r#"
INSERT INTO k_sol_orderbook_events (
    transaction_id,
    decoded_event_id,
    dex_id,
    pool_id,
    pair_id,
    signature,
    slot,
    protocol_name,
    program_id,
    event_kind,
    order_action,
    pool_account,
    market_account,
    actor_wallet,
    order_account,
    base_token_mint,
    quote_token_mint,
    amount_raw,
    amount_min_raw,
    tick_index,
    zero_for_one,
    payload_json,
    executed_at,
    created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                "#,
            )
            .bind(dto.transaction_id)
            .bind(dto.decoded_event_id)
            .bind(dto.dex_id)
            .bind(dto.pool_id)
            .bind(dto.pair_id)
            .bind(dto.signature.clone())
            .bind(slot_i64)
            .bind(dto.protocol_name.clone())
            .bind(dto.program_id.clone())
            .bind(dto.event_kind.clone())
            .bind(dto.order_action.clone())
            .bind(dto.pool_account.clone())
            .bind(dto.market_account.clone())
            .bind(dto.actor_wallet.clone())
            .bind(dto.order_account.clone())
            .bind(dto.base_token_mint.clone())
            .bind(dto.quote_token_mint.clone())
            .bind(dto.amount_raw.clone())
            .bind(dto.amount_min_raw.clone())
            .bind(dto.tick_index)
            .bind(zero_for_one_i64)
            .bind(dto.payload_json.clone())
            .bind(dto.executed_at.to_rfc3339())
            .bind(dto.created_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = insert_result {
                return Err(crate::Error::Db(format!(
                    "cannot insert k_sol_orderbook_events on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_orderbook_events
WHERE transaction_id = ?
  AND protocol_name = ?
  AND event_kind = ?
  AND signature = ?
ORDER BY id DESC
LIMIT 1
                "#,
            )
            .bind(dto.transaction_id)
            .bind(dto.protocol_name.clone())
            .bind(dto.event_kind.clone())
            .bind(dto.signature.clone())
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch inserted k_sol_orderbook_events id for signature '{}' on sqlite: {}",
                        dto.signature, error
                    )));
                },
            }
        },
    }
}
