use serde_json::{Map, Value};

use super::config::{RegistryEngine, VatIdSearchEngine};
use crate::scrape::bizzy::enrich_nl_companies_vat_from_bizzy;
use crate::scrape::kvk::fetch_all_kvk_companies;
use crate::scrape::mapping::{map_kvk_company_to_global, map_northdata_hit_to_global};
use crate::scrape::northdata::fetch_northdata_suggest;

/// Fetch + map to `global_companies_registry` rows (KVK or Northdata).
pub async fn fetch_mapped_global_rows(
    http: &reqwest::Client,
    engine: RegistryEngine,
    query: &str,
    country_code: &str,
    kvk_api_url: &str,
    northdata_base_url: &str,
    northdata_cookie: Option<&str>,
    vat: VatIdSearchEngine,
) -> Vec<Map<String, Value>> {
    let cc = country_code.to_uppercase();
    match engine {
        RegistryEngine::Kvk => {
            let mut companies = fetch_all_kvk_companies(http, kvk_api_url, query).await;
            if matches!(vat, VatIdSearchEngine::Bizzy) {
                enrich_nl_companies_vat_from_bizzy(http, &mut companies).await;
            }
            companies
                .into_iter()
                .filter_map(|c| map_kvk_company_to_global(&c, &cc))
                .collect()
        }
        RegistryEngine::Northdata => {
            let raw =
                fetch_northdata_suggest(http, northdata_base_url, query, &cc, northdata_cookie)
                    .await;
            raw.iter()
                .filter_map(|m| map_northdata_hit_to_global(m, &cc))
                .collect()
        }
    }
}
