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

//! Queries for `k_sol_observed_tokens`.

/// Inserts or updates one observed token by mint.
pub async fn query_observed_tokens_upsert(
    database: &crate::Database,
    dto: &crate::ObservedTokenDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let decimals_i64 = dto.decimals.map(i64::from);
            let insert_result = sqlx::query(
                r#"
INSERT INTO k_sol_observed_tokens (
    mint,
    symbol,
    name,
    decimals,
    token_program,
    status,
    first_seen_at,
    last_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,
    status = excluded.status,
    last_seen_at = excluded.last_seen_at,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.mint.clone())
            .bind(dto.symbol.clone())
            .bind(dto.name.clone())
            .bind(decimals_i64)
            .bind(dto.token_program.clone())
            .bind(dto.status.to_i16())
            .bind(dto.first_seen_at.to_rfc3339())
            .bind(dto.last_seen_at.to_rfc3339())
            .bind(dto.updated_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = insert_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_observed_tokens on sqlite: {}",
                    error
                )));
            }
            let select_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_observed_tokens
WHERE mint = ?
LIMIT 1
                "#,
            )
            .bind(dto.mint.clone())
            .fetch_one(pool)
            .await;
            match select_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_observed_tokens id for mint '{}' on sqlite: {}",
                        dto.mint, error
                    )));
                },
            }
        },
    }
}

/// Reads one observed token by mint.
pub async fn query_observed_tokens_get_by_mint(
    database: &crate::Database,
    mint: &str,
) -> Result<std::option::Option<crate::ObservedTokenDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::ObservedTokenEntity>(
                r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    status,
    first_seen_at,
    last_seen_at,
    updated_at
FROM k_sol_observed_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 observed token '{}' on sqlite: {}",
                        mint, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::ObservedTokenDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Lists observed tokens ordered by newest first.
pub async fn query_observed_tokens_list(
    database: &crate::Database,
    limit: u32,
) -> Result<std::vec::Vec<crate::ObservedTokenDto>, crate::Error> {
    if limit == 0 {
        return Ok(std::vec::Vec::new());
    }
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::ObservedTokenEntity>(
                r#"
SELECT
    id,
    mint,
    symbol,
    name,
    decimals,
    token_program,
    status,
    first_seen_at,
    last_seen_at,
    updated_at
FROM k_sol_observed_tokens
ORDER BY id DESC
LIMIT ?
                    "#,
            )
            .bind(i64::from(limit))
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list observed tokens on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::ObservedTokenDto::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 observed_token_roundtrip_works() {
        let tempdir = tempfile::tempdir().expect("tempdir must succeed");
        let database_path = tempdir.path().join("observed_token.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 dto = crate::ObservedTokenDto::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(),
            crate::ObservedTokenStatus::Active,
        );
        let inserted_id = crate::query_observed_tokens_upsert(&database, &dto)
            .await
            .expect("upsert must succeed");
        assert!(inserted_id > 0);
        let fetched = crate::query_observed_tokens_get_by_mint(&database, crate::WSOL_MINT_ID)
            .await
            .expect("fetch must succeed");
        assert!(fetched.is_some());
        let fetched = fetched.expect("token must exist");
        assert_eq!(fetched.symbol.as_deref(), Some("WSOL"));
        assert_eq!(fetched.decimals, Some(9));
        assert_eq!(fetched.status, crate::ObservedTokenStatus::Active);
        let listed = crate::query_observed_tokens_list(&database, 10)
            .await
            .expect("list must succeed");
        assert_eq!(listed.len(), 1);
    }
}
