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

//! Queries for `k_sol_dexes`.

/// Inserts or updates one normalized DEX row by code.
pub async fn query_dexs_upsert(
    database: &crate::Database,
    dto: &crate::DexDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_dexes (
    code,
    name,
    program_id,
    router_program_id,
    is_enabled,
    created_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(code) DO UPDATE SET
    name = excluded.name,
    program_id = excluded.program_id,
    router_program_id = excluded.router_program_id,
    is_enabled = excluded.is_enabled,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.code.clone())
            .bind(dto.name.clone())
            .bind(dto.program_id.clone())
            .bind(dto.router_program_id.clone())
            .bind(if dto.is_enabled { 1_i64 } else { 0_i64 })
            .bind(dto.created_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_dexes on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_dexes
WHERE code = ?
LIMIT 1
                "#,
            )
            .bind(dto.code.clone())
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_dexes id for code '{}' on sqlite: {}",
                        dto.code, error
                    )));
                },
            }
        },
    }
}

/// Reads one normalized DEX row by code.
pub async fn query_dexs_get_by_code(
    database: &crate::Database,
    code: &str,
) -> Result<std::option::Option<crate::DexDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::DexEntity>(
                r#"
SELECT
    id,
    code,
    name,
    program_id,
    router_program_id,
    is_enabled,
    created_at,
    updated_at
FROM k_sol_dexes
WHERE code = ?
LIMIT 1
                "#,
            )
            .bind(code)
            .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_dexes '{}' on sqlite: {}",
                        code, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::DexDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Lists normalized DEX rows.
pub async fn query_dexs_list(
    database: &crate::Database,
) -> Result<std::vec::Vec<crate::DexDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::DexEntity>(
                r#"
SELECT
    id,
    code,
    name,
    program_id,
    router_program_id,
    is_enabled,
    created_at,
    updated_at
FROM k_sol_dexes
ORDER BY code 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_dexes on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::DexDto::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 dex_roundtrip_works() {
        let tempdir = tempfile::tempdir().expect("tempdir must succeed");
        let database_path = tempdir.path().join("dex_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");
        assert!(dex_id > 0);
        let dex = crate::query_dexs_get_by_code(&database, "raydium_amm_v4")
            .await
            .expect("get dex must succeed");
        assert!(dex.is_some());
        assert_eq!(dex.expect("dex must exist").name, "Raydium AMM v4");
        let dexes = crate::query_dexs_list(&database).await.expect("list dexes must succeed");
        assert_eq!(dexes.len(), 1);
    }
}
