//! Regression for the `Registry.type_def_module` re-key (ctt.2).
//!
//! Two modules each declare `type Foo` with distinct ctors and
//! provide an `instance MyC Foo`. Pre-ctt.2, both bare `Foo`s
//! collide on the bare-name `BTreeMap<String, String>` key —
//! `normalize_type_for_registry` qualifies both to whichever
//! module won the insert race, and the loser's instance trips
//! a false `DuplicateInstance`. Post-ctt.2, the tuple-keyed map
//! distinguishes the two `Foo`s by owning module; both instances
//! register cleanly under distinct canonical keys.
//!
//! This test goes red today (DuplicateInstance) and green after
//! the re-key.

use ailang_core::canonical;
use ailang_core::ast::Type;
use ailang_surface::load_workspace;
use ailang_test_support::examples_dir;

#[test]
fn two_modules_with_same_bare_foo_both_register() {
    let entry = examples_dir().join("ctt2_collision_main.ail");
    let ws = load_workspace(&entry)
        .expect("expected workspace load to succeed; both `type Foo` declarations live in distinct modules and must register under distinct canonical keys");

    // Compute the canonical type hashes for the two expected entries.
    let main_foo_hash = canonical::type_hash(&Type::Con {
        name: "ctt2_collision_main.Foo".into(),
        args: vec![],
    });
    let lib_foo_hash = canonical::type_hash(&Type::Con {
        name: "ctt2_collision_lib.Foo".into(),
        args: vec![],
    });

    // registry-entries key is keyed by the qualified class name.
    let main_key = ("ctt2_collision_cls.MyC".to_string(), main_foo_hash);
    let lib_key = ("ctt2_collision_cls.MyC".to_string(), lib_foo_hash);

    assert!(
        ws.registry.entries.contains_key(&main_key),
        "registry missing entry for (MyC, ctt2_collision_main.Foo); entries: {:?}",
        ws.registry.entries.keys().collect::<Vec<_>>()
    );
    assert!(
        ws.registry.entries.contains_key(&lib_key),
        "registry missing entry for (MyC, ctt2_collision_lib.Foo); entries: {:?}",
        ws.registry.entries.keys().collect::<Vec<_>>()
    );

    // Defining-module sanity: each entry's defining_module matches
    // the module that wrote the instance.
    let main_entry = &ws.registry.entries[&main_key];
    assert_eq!(
        main_entry.defining_module, "ctt2_collision_main",
        "main-side entry's defining_module mismatched"
    );
    let lib_entry = &ws.registry.entries[&lib_key];
    assert_eq!(
        lib_entry.defining_module, "ctt2_collision_lib",
        "lib-side entry's defining_module mismatched"
    );
}
