game_manager_lib\commands\metadata/
shared.rs

1//! Módulo compartilhado para enriquecimento de metadados
2//!
3//! Contém estruturas e funções reutilizadas por enrichment e covers.
4
5use crate::services::{cache, rawg};
6
7// === ESTRUTURAS COMPARTILHADAS ===
8
9/// Progresso de enriquecimento de metadados
10#[derive(serde::Serialize, Clone)]
11pub struct EnrichProgress {
12    pub current: i32,
13    pub total_found: i32,
14    pub last_game: String,
15    pub status: String,
16}
17
18// === FUNÇÕES COMPARTILHADAS ===
19
20/// Busca metadados RAWG com cache
21///
22/// Esta função é compartilhada entre enrichment e covers
23/// para buscar informações de jogos na API RAWG com suporte a cache SQLite.
24pub async fn fetch_rawg_metadata(
25    api_key: &str,
26    name: &str,
27    cache_conn: &rusqlite::Connection,
28) -> Option<rawg::GameDetails> {
29    // Tenta buscar no cache primeiro
30    let cache_key = format!("search_{}", name.to_lowercase());
31
32    if let Some(cached) = cache::get_cached_api_data(cache_conn, "rawg", &cache_key) {
33        if let Ok(details) = serde_json::from_str::<rawg::GameDetails>(&cached) {
34            return Some(details);
35        }
36    }
37
38    // Se não está em cache, busca na API
39    match rawg::search_games(api_key, name).await {
40        Ok(results) => {
41            if let Some(best_match) = results.first() {
42                match rawg::fetch_game_details(api_key, best_match.id.to_string()).await {
43                    Ok(details) => {
44                        // Salva no cache
45                        if let Ok(json) = serde_json::to_string(&details) {
46                            let _ =
47                                cache::save_cached_api_data(cache_conn, "rawg", &cache_key, &json);
48                        }
49                        Some(details)
50                    }
51                    Err(_) => None,
52                }
53            } else {
54                None
55            }
56        }
57        Err(_) => None,
58    }
59}