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

//! Queries for `k_sol_token_mint_events`.

/// Inserts or updates one normalized token mint event row.
pub async fn query_token_mint_events_upsert(
    database: &crate::Database,
    dto: &crate::TokenMintEventDto,
) -> 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 token mint event slot '{}' to i64: {}",
                        slot, error
                    )));
                },
            }
        },
        None => None,
    };
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_token_mint_events (
    token_id,
    signature,
    instruction_index,
    slot,
    authority_wallet,
    destination_wallet,
    amount,
    supply_after,
    executed_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(signature, instruction_index) DO UPDATE SET
    token_id = excluded.token_id,
    slot = excluded.slot,
    authority_wallet = excluded.authority_wallet,
    destination_wallet = excluded.destination_wallet,
    amount = excluded.amount,
    supply_after = excluded.supply_after,
    executed_at = excluded.executed_at
                "#,
            )
            .bind(dto.token_id)
            .bind(dto.signature.clone())
            .bind(dto.instruction_index)
            .bind(slot_i64)
            .bind(dto.authority_wallet.clone())
            .bind(dto.destination_wallet.clone())
            .bind(dto.amount.clone())
            .bind(dto.supply_after.clone())
            .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_token_mint_events on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_token_mint_events
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_token_mint_events id for signature '{}' and instruction_index '{}' on sqlite: {}",
                        dto.signature, dto.instruction_index, error
                    )));
                },
            }
        },
    }
}

/// Lists recent token mint events ordered from newest to oldest.
pub async fn query_token_mint_events_list_recent(
    database: &crate::Database,
    limit: u32,
) -> Result<std::vec::Vec<crate::TokenMintEventDto>, 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::TokenMintEventEntity>(
                r#"
SELECT
    id,
    token_id,
    signature,
    instruction_index,
    slot,
    authority_wallet,
    destination_wallet,
    amount,
    supply_after,
    executed_at
FROM k_sol_token_mint_events
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_token_mint_events on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::TokenMintEventDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
