//! Shared test helpers for tree tests
//!
//! This module contains common utilities used across multiple test modules
//! to reduce duplication and ensure consistency.

use std::sync::Arc;

use ordermap::OrderMap;

use crate::catalog::CatalogProvider;
use crate::err::WithTranslationErrors;
use crate::tree::ast::dataset_identifier::DatasetIdentifier;
use crate::tree::ast::identifier::SimpleIdentifier as AstSimpleIdentifier;
use crate::tree::ast::TypeCheck;
use crate::tree::options::TypeCheckOptions;
use crate::type_check_with_options;
use crate::types::Type;

/// Helper to create a catalog provider with table schemas.
///
/// Unqualified table names are registered under the unit-test default space `test`.
pub fn catalog_with_tables(tables: Vec<(&str, Vec<(&str, Type)>)>) -> Arc<CatalogProvider> {
    let mut datasets = std::collections::HashMap::new();
    let default_space = AstSimpleIdentifier::new("test");

    for (table_name, fields) in tables {
        let table_id = DatasetIdentifier::from_ref_str(table_name)
            .unwrap()
            .qualify(Some(&default_space))
            .unwrap();
        let mut field_map = OrderMap::new();
        for (field_name, field_type) in fields {
            field_map.insert(AstSimpleIdentifier::new(field_name), field_type);
        }
        datasets.insert(table_id, field_map);
    }

    Arc::new(CatalogProvider::new(datasets))
}

/// Type-check with a test catalog and the unit-test default space `test`.
pub fn type_check_with_catalog<Ast: TypeCheck>(
    ast: impl Into<Arc<Ast>>,
    catalog: Arc<CatalogProvider>,
) -> WithTranslationErrors<Ast::Output> {
    type_check_with_options(
        ast,
        TypeCheckOptions::builder()
            .provider(catalog)
            .maybe_default_space(Some(AstSimpleIdentifier::new("test")))
            .build(),
    )
}
