from types import SimpleNamespace

import pytest

from nemo_library_etl.adapter.migman.migmanutils import MigManUtils


def test_split_migman_project_name_with_and_without_postfix() -> None:
    project, postfix = MigManUtils.split_migman_project_name("Customers")
    assert project == "Customers"
    assert postfix == ""

    project, postfix = MigManUtils.split_migman_project_name("Customers:DE")
    assert project == "Customers"
    assert postfix == "DE"


def test_get_allowed_import_fields_returns_ordered_distinct_fields(monkeypatch) -> None:
    fake_db = [
        SimpleNamespace(project="Customers", postfix="", nemo_import_name="Name1", index=2),
        SimpleNamespace(project="Customers", postfix="", nemo_import_name="Kundennummer", index=1),
        SimpleNamespace(project="Customers", postfix="", nemo_import_name="Name1", index=3),
        SimpleNamespace(project="Suppliers", postfix="", nemo_import_name="Lieferant", index=1),
    ]

    monkeypatch.setattr(
        MigManUtils,
        "MigManDatabaseLoad",
        staticmethod(lambda: fake_db),
    )

    fields = MigManUtils.get_allowed_import_fields("Customers")

    assert fields == ["Kundennummer", "Name1"]


def test_validate_columns_raises_for_missing_and_additional_columns(monkeypatch) -> None:
    fake_db = [
        SimpleNamespace(project="Customers", postfix="", nemo_import_name="Kundennummer"),
        SimpleNamespace(project="Customers", postfix="", nemo_import_name="Name1"),
    ]

    monkeypatch.setattr(
        MigManUtils,
        "MigManDatabaseLoad",
        staticmethod(lambda: fake_db),
    )

    with pytest.raises(ValueError) as exc_info:
        MigManUtils.validate_columns(
            project="Customers",
            postfix="",
            columns=["Kundennummer", "ExtraSpalte"],
        )

    message = str(exc_info.value)
    assert "Column mismatch for project 'Customers' and postfix ''" in message
    assert "Missing" in message
    assert "Name1" in message
    assert "Unexpected" in message
    assert "ExtraSpalte" in message

def test_generate_join_stub_sql_contains_expected_null_aliases() -> None:
    sql = MigManUtils.generate_join_stub_sql(
        "Customers",
        fields=["Kundennummer", "Name1"],
    )

    assert sql.startswith("SELECT")
    assert 'NULL AS "Kundennummer"' in sql
    assert 'NULL AS "Name1"' in sql