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

//! Queries for `k_sol_pool_listings`.

/// Inserts or updates one normalized pool listing row by pool id.
pub async fn query_pool_listings_upsert(
    database: &crate::Database,
    dto: &crate::PoolListingDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_pool_listings (
    dex_id,
    pool_id,
    pair_id,
    source_kind,
    source_endpoint_name,
    detected_at,
    initial_base_reserve,
    initial_quote_reserve,
    initial_price_quote,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(pool_id) DO UPDATE SET
    dex_id = excluded.dex_id,
    pair_id = excluded.pair_id,
    source_kind = excluded.source_kind,
    source_endpoint_name = excluded.source_endpoint_name,
    detected_at = excluded.detected_at,
    initial_base_reserve = excluded.initial_base_reserve,
    initial_quote_reserve = excluded.initial_quote_reserve,
    initial_price_quote = excluded.initial_price_quote,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.dex_id)
            .bind(dto.pool_id)
            .bind(dto.pair_id)
            .bind(dto.source_kind.to_i16())
            .bind(dto.source_endpoint_name.clone())
            .bind(dto.detected_at.to_rfc3339())
            .bind(dto.initial_base_reserve)
            .bind(dto.initial_quote_reserve)
            .bind(dto.initial_price_quote)
            .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_pool_listings on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_pool_listings
WHERE pool_id = ?
LIMIT 1
                "#,
            )
            .bind(dto.pool_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_pool_listings id for pool_id '{}' on sqlite: {}",
                        dto.pool_id, error
                    )));
                },
            }
        },
    }
}

/// Reads one normalized pool listing row by pool id.
pub async fn query_pool_listings_get_by_pool_id(
    database: &crate::Database,
    pool_id: i64,
) -> Result<std::option::Option<crate::PoolListingDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::PoolListingEntity>(
                r#"
SELECT
    id,
    dex_id,
    pool_id,
    pair_id,
    source_kind,
    source_endpoint_name,
    detected_at,
    initial_base_reserve,
    initial_quote_reserve,
    initial_price_quote,
    updated_at
FROM k_sol_pool_listings
WHERE pool_id = ?
LIMIT 1
                "#,
            )
            .bind(pool_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_pool_listings by pool_id '{}' on sqlite: {}",
                        pool_id, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::PoolListingDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Lists normalized pool listings ordered by detected date then id.
pub async fn query_pool_listings_list(
    database: &crate::Database,
) -> Result<std::vec::Vec<crate::PoolListingDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::PoolListingEntity>(
                r#"
SELECT
    id,
    dex_id,
    pool_id,
    pair_id,
    source_kind,
    source_endpoint_name,
    detected_at,
    initial_base_reserve,
    initial_quote_reserve,
    initial_price_quote,
    updated_at
FROM k_sol_pool_listings
ORDER BY detected_at ASC, id ASC
                "#,
            )
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_pool_listings on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::PoolListingDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn pool_listing_roundtrip_works() {
        let tempdir = tempfile::tempdir().expect("tempdir must succeed");
        let database_path = tempdir.path().join("pool_listing_roundtrip.sqlite3");
        let config = crate::DatabaseConfig {
            enabled: true,
            backend: crate::DatabaseBackend::Sqlite,
            sqlite: crate::SqliteDatabaseConfig {
                path: database_path.to_string_lossy().to_string(),
                create_if_missing: true,
                busy_timeout_ms: 5000,
                max_connections: 1,
                auto_initialize_schema: true,
                use_wal: true,
            },
        };
        let database = crate::Database::connect_and_initialize(&config)
            .await
            .expect("database init must succeed");
        let dex_id = crate::query_dexs_upsert(
            &database,
            &crate::DexDto::new("raydium_amm_v4".to_string(), "Raydium AMM v4".to_string(), None, None, true),
        )
        .await
        .expect("dex upsert must succeed");
        let base_token_id = crate::query_tokens_upsert(
            &database,
            &crate::TokenDto::new(
                "Base111111111111111111111111111111111111111".to_string(),
                Some("BASE".to_string()),
                Some("Base Token".to_string()),
                Some(6),
                crate::SPL_TOKEN_PROGRAM_ID.to_string(),
                false,
            ),
        )
        .await
        .expect("base token upsert must succeed");
        let quote_token_id = crate::query_tokens_upsert(
            &database,
            &crate::TokenDto::new(
                crate::WSOL_MINT_ID.to_string(),
                Some("WSOL".to_string()),
                Some("Wrapped SOL".to_string()),
                Some(9),
                crate::SPL_TOKEN_PROGRAM_ID.to_string(),
                true,
            ),
        )
        .await
        .expect("quote token upsert must succeed");
        let pool_id = crate::query_pools_upsert(
            &database,
            &crate::PoolDto::new(
                dex_id,
                "Pool111111111111111111111111111111111111111".to_string(),
                crate::PoolKind::Amm,
                crate::PoolStatus::Active,
            ),
        )
        .await
        .expect("pool upsert must succeed");
        let pair_id = crate::query_pairs_upsert(
            &database,
            &crate::PairDto::new(
                dex_id,
                pool_id,
                base_token_id,
                quote_token_id,
                Some("BASE/WSOL".to_string()),
            ),
        )
        .await
        .expect("pair upsert must succeed");
        let pool_listing_id = crate::query_pool_listings_upsert(
            &database,
            &crate::PoolListingDto::new(
                dex_id,
                pool_id,
                Some(pair_id),
                crate::ObservationSourceKind::WsRpc,
                Some("mainnet_public_ws_slots".to_string()),
                Some(1000.0),
                Some(10.0),
                Some(0.01),
            ),
        )
        .await
        .expect("pool listing upsert must succeed");
        assert!(pool_listing_id > 0);
        let pool_listing = crate::query_pool_listings_get_by_pool_id(&database, pool_id)
            .await
            .expect("get pool listing must succeed");
        assert!(pool_listing.is_some());
        assert_eq!(
            pool_listing.expect("pool listing must exist").source_kind,
            crate::ObservationSourceKind::WsRpc
        );
        let pool_listings = crate::query_pool_listings_list(&database)
            .await
            .expect("list pool listings must succeed");
        assert_eq!(pool_listings.len(), 1);
    }
}
