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

//! Queries for `k_sol_pairs`.

/// Inserts or updates one normalized pair row by pool id.
pub async fn query_pairs_upsert(
    database: &crate::Database,
    dto: &crate::PairDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_pairs (
    dex_id,
    pool_id,
    base_token_id,
    quote_token_id,
    symbol,
    first_seen_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(pool_id) DO UPDATE SET
    dex_id = excluded.dex_id,
    base_token_id = excluded.base_token_id,
    quote_token_id = excluded.quote_token_id,
    symbol = CASE
        WHEN excluded.symbol IS NOT NULL AND trim(excluded.symbol) <> ''
        THEN excluded.symbol
        ELSE k_sol_pairs.symbol
    END,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.dex_id)
            .bind(dto.pool_id)
            .bind(dto.base_token_id)
            .bind(dto.quote_token_id)
            .bind(dto.symbol.clone())
            .bind(dto.first_seen_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_pairs on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_pairs
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_pairs id for pool_id '{}' on sqlite: {}",
                        dto.pool_id, error
                    )));
                },
            }
        },
    }
}

/// Reads one normalized pair row by pool id.
pub async fn query_pairs_get_by_pool_id(
    database: &crate::Database,
    pool_id: i64,
) -> Result<std::option::Option<crate::PairDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::PairEntity>(
                r#"
SELECT
    id,
    dex_id,
    pool_id,
    base_token_id,
    quote_token_id,
    symbol,
    first_seen_at,
    updated_at
FROM k_sol_pairs
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_pairs by pool_id '{}' on sqlite: {}",
                        pool_id, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::PairDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Updates the display symbol of one normalized pair row.
pub async fn query_pairs_update_symbol(
    database: &crate::Database,
    pair_id: i64,
    symbol: std::option::Option<&str>,
) -> Result<bool, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
UPDATE k_sol_pairs
SET
    symbol = ?,
    updated_at = ?
WHERE id = ?
                "#,
            )
            .bind(symbol)
            .bind(chrono::Utc::now().to_rfc3339())
            .bind(pair_id)
            .execute(pool)
            .await;
            match query_result {
                Ok(done) => return Ok(done.rows_affected() > 0),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot update k_sol_pairs symbol for id '{}' on sqlite: {}",
                        pair_id, error
                    )));
                },
            }
        },
    }
}

/// Lists normalized pairs ordered by id ascending.
pub async fn query_pairs_list(
    database: &crate::Database,
) -> Result<std::vec::Vec<crate::PairDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::PairEntity>(
                r#"
SELECT
    id,
    dex_id,
    pool_id,
    base_token_id,
    quote_token_id,
    symbol,
    first_seen_at,
    updated_at
FROM k_sol_pairs
ORDER BY 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_pairs on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::PairDto::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 pair_roundtrip_works() {
        let tempdir = tempfile::tempdir().expect("tempdir must succeed");
        let database_path = tempdir.path().join("pair_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");
        assert!(pair_id > 0);
        let pair = crate::query_pairs_get_by_pool_id(&database, pool_id)
            .await
            .expect("get pair must succeed");
        assert!(pair.is_some());
        assert_eq!(pair.expect("pair must exist").symbol.as_deref(), Some("BASE/WSOL"));
        let pairs = crate::query_pairs_list(&database).await.expect("list pairs must succeed");
        assert_eq!(pairs.len(), 1);
    }
}
