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

//! Queries for `k_sol_tokens`.

/// Inserts or updates one normalized token row by mint.
pub async fn query_tokens_upsert(
    database: &crate::Database,
    dto: &crate::TokenDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let decimals = dto.decimals.map(i64::from);
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_tokens (
    mint,
    symbol,
    name,
    decimals,
    token_program,
    is_quote_token,
    first_seen_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(mint) DO UPDATE SET
    symbol = excluded.symbol,
    name = excluded.name,
    decimals = excluded.decimals,
    token_program = excluded.token_program,
    is_quote_token = excluded.is_quote_token,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.mint.clone())
            .bind(dto.symbol.clone())
            .bind(dto.name.clone())
            .bind(decimals)
            .bind(dto.token_program.clone())
            .bind(if dto.is_quote_token { 1_i64 } else { 0_i64 })
            .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_tokens on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_tokens
WHERE mint = ?
LIMIT 1
                "#,
            )
            .bind(dto.mint.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_tokens id for mint '{}' on sqlite: {}",
                        dto.mint, error
                    )));
                },
            }
        },
    }
}

/// Reads one normalized token row by mint.
pub async fn query_tokens_get_by_mint(
    database: &crate::Database,
    mint: &str,
) -> Result<std::option::Option<crate::TokenDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::TokenEntity>(
                r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    is_quote_token,
    first_seen_at,
    updated_at
FROM k_sol_tokens
WHERE mint = ?
LIMIT 1
                "#,
            )
            .bind(mint)
            .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_tokens '{}' on sqlite: {}",
                        mint, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::TokenDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Reads one normalized token row by internal id.
pub async fn query_tokens_get_by_id(
    database: &crate::Database,
    token_id: i64,
) -> Result<std::option::Option<crate::TokenDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::TokenEntity>(
                r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    is_quote_token,
    first_seen_at,
    updated_at
FROM k_sol_tokens
WHERE id = ?
LIMIT 1
                "#,
            )
            .bind(token_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_tokens id '{}' on sqlite: {}",
                        token_id, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::TokenDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Lists all normalized token rows ordered by mint.
pub async fn query_tokens_list(
    database: &crate::Database,
) -> Result<std::vec::Vec<crate::TokenDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::TokenEntity>(
                r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    is_quote_token,
    first_seen_at,
    updated_at
FROM k_sol_tokens
ORDER BY mint 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_tokens on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::TokenDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}

/// Lists token rows whose display or mint metadata is incomplete.
pub async fn query_tokens_list_missing_metadata(
    database: &crate::Database,
    limit: std::option::Option<i64>,
) -> Result<std::vec::Vec<crate::TokenDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let entities_result = match limit {
                Some(limit) => {
                    sqlx::query_as::<sqlx::Sqlite, crate::TokenEntity>(
                        r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    is_quote_token,
    first_seen_at,
    updated_at
FROM k_sol_tokens
WHERE symbol IS NULL
   OR trim(symbol) = ''
   OR name IS NULL
   OR trim(name) = ''
   OR decimals IS NULL
   OR token_program IS NULL
   OR trim(token_program) = ''
ORDER BY updated_at ASC, id ASC
LIMIT ?
                        "#,
                    )
                    .bind(limit)
                    .fetch_all(pool)
                    .await
                },
                None => {
                    sqlx::query_as::<sqlx::Sqlite, crate::TokenEntity>(
                        r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    is_quote_token,
    first_seen_at,
    updated_at
FROM k_sol_tokens
WHERE symbol IS NULL
   OR trim(symbol) = ''
   OR name IS NULL
   OR trim(name) = ''
   OR decimals IS NULL
   OR token_program IS NULL
   OR trim(token_program) = ''
ORDER BY updated_at ASC, id ASC
                        "#,
                    )
                    .fetch_all(pool)
                    .await
                },
            };
            let entities = match entities_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_tokens missing metadata on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::TokenDto::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 {
    async fn make_database() -> std::sync::Arc<crate::Database> {
        let tempdir_result = tempfile::tempdir();
        let tempdir = match tempdir_result {
            Ok(tempdir) => tempdir,
            Err(error) => panic!("tempdir must succeed: {}", error),
        };
        let database_path = tempdir.path().join("token_query.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_result = crate::Database::connect_and_initialize(&config).await;
        let database = match database_result {
            Ok(database) => database,
            Err(error) => panic!("database init must succeed: {}", error),
        };
        return std::sync::Arc::new(database);
    }

    #[tokio::test]
    async fn list_tokens_missing_metadata_only_returns_incomplete_rows() {
        let database = make_database().await;
        let incomplete = crate::TokenDto::new(
            "IncompleteMint111".to_string(),
            None,
            None,
            None,
            crate::SPL_TOKEN_PROGRAM_ID.to_string(),
            false,
        );
        let complete = crate::TokenDto::new(
            "CompleteMint111".to_string(),
            Some("CMP".to_string()),
            Some("Complete".to_string()),
            Some(6),
            crate::SPL_TOKEN_PROGRAM_ID.to_string(),
            false,
        );
        let incomplete_result = crate::query_tokens_upsert(database.as_ref(), &incomplete).await;
        if let Err(error) = incomplete_result {
            panic!("incomplete token upsert must succeed: {}", error);
        }
        let complete_result = crate::query_tokens_upsert(database.as_ref(), &complete).await;
        if let Err(error) = complete_result {
            panic!("complete token upsert must succeed: {}", error);
        }
        let missing_result =
            crate::query_tokens_list_missing_metadata(database.as_ref(), None).await;
        let missing = match missing_result {
            Ok(missing) => missing,
            Err(error) => panic!("missing metadata list must succeed: {}", error),
        };
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].mint, "IncompleteMint111");
    }
}
