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

//! Queries for `k_sol_launch_attributions`.

/// Inserts or updates one launch attribution row and returns its stable internal id.
pub async fn query_launch_attributions_upsert(
    database: &crate::Database,
    dto: &crate::LaunchAttributionDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_launch_attributions (
    launch_surface_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    matched_key_id,
    protocol_name,
    match_kind,
    matched_value,
    attributed_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(decoded_event_id) DO UPDATE SET
    launch_surface_id = excluded.launch_surface_id,
    transaction_id = excluded.transaction_id,
    pool_id = excluded.pool_id,
    pair_id = excluded.pair_id,
    matched_key_id = excluded.matched_key_id,
    protocol_name = excluded.protocol_name,
    match_kind = excluded.match_kind,
    matched_value = excluded.matched_value,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.launch_surface_id)
            .bind(dto.transaction_id)
            .bind(dto.decoded_event_id)
            .bind(dto.pool_id)
            .bind(dto.pair_id)
            .bind(dto.matched_key_id)
            .bind(dto.protocol_name.clone())
            .bind(dto.match_kind.clone())
            .bind(dto.matched_value.clone())
            .bind(dto.attributed_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_launch_attributions on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_launch_attributions
WHERE decoded_event_id = ?
LIMIT 1
                "#,
            )
            .bind(dto.decoded_event_id)
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_launch_attributions id for decoded_event_id '{}' on sqlite: {}",
                        dto.decoded_event_id, error
                    )));
                },
            }
        },
    }
}

/// Returns one launch attribution identified by its decoded-event id, if it exists.
pub async fn query_launch_attributions_get_by_decoded_event_id(
    database: &crate::Database,
    decoded_event_id: i64,
) -> Result<std::option::Option<crate::LaunchAttributionDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::LaunchAttributionEntity>(
                r#"
SELECT
    id,
    launch_surface_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    matched_key_id,
    protocol_name,
    match_kind,
    matched_value,
    attributed_at,
    updated_at
FROM k_sol_launch_attributions
WHERE decoded_event_id = ?
LIMIT 1
                    "#,
            )
            .bind(decoded_event_id)
            .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_launch_attributions by decoded_event_id '{}' on sqlite: {}",
                        decoded_event_id, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => return crate::LaunchAttributionDto::try_from(entity).map(Some),
                None => return Ok(None),
            }
        },
    }
}

/// Lists all launch attributions attached to one pool id.
pub async fn query_launch_attributions_list_by_pool_id(
    database: &crate::Database,
    pool_id: i64,
) -> Result<std::vec::Vec<crate::LaunchAttributionDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::LaunchAttributionEntity>(
                r#"
SELECT
    id,
    launch_surface_id,
    transaction_id,
    decoded_event_id,
    pool_id,
    pair_id,
    matched_key_id,
    protocol_name,
    match_kind,
    matched_value,
    attributed_at,
    updated_at
FROM k_sol_launch_attributions
WHERE pool_id = ?
ORDER BY attributed_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_launch_attributions by pool_id '{}' on sqlite: {}",
                        pool_id, error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::LaunchAttributionDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
