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

//! Queries for `k_sol_launch_events`.

/// Inserts or updates one launch event by decoded event id.
pub async fn query_launch_events_upsert(
    database: &crate::Database,
    input: &crate::LaunchEventUpsertInput,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let existing_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_launch_events
WHERE decoded_event_id = ?
LIMIT 1
                "#,
            )
            .bind(input.decoded_event_id)
            .fetch_optional(pool)
            .await;
            let existing_id = match existing_result {
                Ok(existing_id) => existing_id,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_launch_events id for decoded_event_id '{}' on sqlite: {}",
                        input.decoded_event_id, error
                    )));
                },
            };
            if let Some(existing_id) = existing_id {
                let update_result = sqlx::query(
                    r#"
UPDATE k_sol_launch_events
SET
    transaction_id = ?,
    dex_id = ?,
    pool_id = ?,
    pair_id = ?,
    signature = ?,
    slot = ?,
    protocol_name = ?,
    program_id = ?,
    event_kind = ?,
    pool_account = ?,
    actor_wallet = ?,
    event_role = ?,
    related_account = ?,
    related_mint = ?,
    payload_json = ?,
    executed_at = ?
WHERE id = ?
                    "#,
                )
                .bind(input.transaction_id)
                .bind(input.dex_id)
                .bind(input.pool_id)
                .bind(input.pair_id)
                .bind(input.signature.clone())
                .bind(input.slot)
                .bind(input.protocol_name.clone())
                .bind(input.program_id.clone())
                .bind(input.event_kind.clone())
                .bind(input.pool_account.clone())
                .bind(input.actor_wallet.clone())
                .bind(input.event_role.clone())
                .bind(input.related_account.clone())
                .bind(input.related_mint.clone())
                .bind(input.payload_json.clone())
                .bind(chrono::Utc::now().to_rfc3339())
                .bind(existing_id)
                .execute(pool)
                .await;
                if let Err(error) = update_result {
                    return Err(crate::Error::Db(format!(
                        "cannot update k_sol_launch_events id '{}' on sqlite: {}",
                        existing_id, error
                    )));
                }
                return Ok(existing_id);
            }
            let insert_result = sqlx::query(
                r#"
INSERT INTO k_sol_launch_events (
    transaction_id,
    decoded_event_id,
    dex_id,
    pool_id,
    pair_id,
    signature,
    slot,
    protocol_name,
    program_id,
    event_kind,
    pool_account,
    actor_wallet,
    event_role,
    related_account,
    related_mint,
    payload_json,
    executed_at,
    created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                "#,
            )
            .bind(input.transaction_id)
            .bind(input.decoded_event_id)
            .bind(input.dex_id)
            .bind(input.pool_id)
            .bind(input.pair_id)
            .bind(input.signature.clone())
            .bind(input.slot)
            .bind(input.protocol_name.clone())
            .bind(input.program_id.clone())
            .bind(input.event_kind.clone())
            .bind(input.pool_account.clone())
            .bind(input.actor_wallet.clone())
            .bind(input.event_role.clone())
            .bind(input.related_account.clone())
            .bind(input.related_mint.clone())
            .bind(input.payload_json.clone())
            .bind(chrono::Utc::now().to_rfc3339())
            .bind(chrono::Utc::now().to_rfc3339())
            .execute(pool)
            .await;
            match insert_result {
                Ok(result) => return Ok(result.last_insert_rowid()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot insert k_sol_launch_events on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}
