use edifact_mapper::{DataDir, Mapper, MapperError};

#[test]
fn test_data_dir_auto_with_env_var() {
    // DataDir::auto() reads EDIFACT_DATA_DIR — test the explicit path API instead
    // to avoid mutating shared env vars across parallel tests.
    let dir = DataDir::path("/tmp/test-edifact-data");
    assert_eq!(dir.data_path().to_str().unwrap(), "/tmp/test-edifact-data");
}

#[test]
fn test_data_dir_explicit_path() {
    let dir = DataDir::path("/opt/edifact");
    assert_eq!(dir.data_path().to_str().unwrap(), "/opt/edifact");
}

#[test]
fn test_data_dir_bundle_path() {
    let dir = DataDir::path("/data");
    assert_eq!(
        dir.bundle_path("FV2504").to_str().unwrap(),
        "/data/edifact-data-FV2504.bin"
    );
}

#[test]
fn test_data_dir_eager_chaining() {
    let dir = DataDir::path("/data").eager(&["FV2504", "FV2510"]);
    assert_eq!(dir.eager_fvs(), &["FV2504", "FV2510"]);
}

#[test]
fn test_mapper_missing_bundle() {
    let dir = DataDir::path("/nonexistent/path");
    let mapper = Mapper::from_data_dir(dir).unwrap();
    match mapper.conversion_service("FV2504", "UTILMD_Strom") {
        Err(MapperError::BundleNotFound { .. }) => {} // expected
        Err(e) => panic!("Expected BundleNotFound, got: {e}"),
        Ok(_) => panic!("Expected error, got Ok"),
    }
}

#[test]
fn test_mapper_eager_missing_bundle_fails() {
    let dir = DataDir::path("/nonexistent/path").eager(&["FV2504"]);
    match Mapper::from_data_dir(dir) {
        Err(MapperError::BundleNotFound { .. }) => {} // expected
        Err(e) => panic!("Expected BundleNotFound, got: {e}"),
        Ok(_) => panic!("Expected error, got Ok"),
    }
}

#[test]
fn test_mapper_no_bundles_loaded_initially() {
    let dir = DataDir::path("/nonexistent/path");
    let mapper = Mapper::from_data_dir(dir).unwrap();
    assert!(mapper.loaded_format_versions().is_empty());
}

/// Integration test that only runs when a compatible bundle is present.
/// Generate bundles with: `cargo run -p automapper-generator -- bundle-data ...`
#[test]
fn test_mapper_from_real_bundle() {
    let bundle_dir = std::path::Path::new("/tmp/edifact-bundles");
    if !bundle_dir.join("edifact-data-FV2504.bin").exists() {
        eprintln!("Skipping: no bundle at /tmp/edifact-bundles");
        return;
    }
    let mapper = match Mapper::from_data_dir(DataDir::path(bundle_dir).eager(&["FV2504"])) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("Skipping: bundle load failed (possibly incompatible version): {e}");
            return;
        }
    };
    let variants = mapper.variants("FV2504").unwrap();
    assert!(variants.contains(&"UTILMD_Strom".to_string()));
    let engine = mapper.engine("FV2504", "UTILMD_Strom", "55001").unwrap();
    assert!(!engine.definitions().is_empty());
}
