from db.product_browser import _compact_fields
from db.product_matrix_display import (
    polish_magento_matrix_fields,
    polish_plytix_matrix_fields,
    sort_matrix_field_keys,
)


def test_compact_fields_truncates_long_values():
    fields = {"sku": "A", "description": "x" * 300}
    compact = _compact_fields(fields, max_fields=10)
    assert compact is not None
    assert len(compact["description"]) <= 240


def test_polish_plytix_matrix_fields_renames_internal_id():
    polished = polish_plytix_matrix_fields(
        {"sku": "A", "id": "68e48b793a9e4244d774f39f", "label": "Cabinet"}
    )
    assert polished["plytix_product_id"] == "68e48b793a9e4244d774f39f"
    assert "id" not in polished


def test_polish_magento_matrix_fields_renames_id_and_resolves_option_label():
    polished = polish_magento_matrix_fields(
        {"sku": "A", "id": 4468, "magento_door_style": "520"},
        option_labels_by_code={"door_style": {520: "Shaker"}},
    )
    assert polished["magento_product_id"] == 4468
    assert polished["magento_door_style"] == "Shaker (520)"
    assert "id" not in polished


def test_sort_matrix_field_keys_puts_meta_last():
    ordered = sort_matrix_field_keys(
        ["plytix_product_id", "brand", "label", "magento_product_id", "price"]
    )
    assert ordered == ["brand", "label", "price", "magento_product_id", "plytix_product_id"]


def test_compact_fields_puts_meta_ids_after_business_fields():
    fields = {
        "sku": "A",
        "plytix_product_id": "68e48",
        "label": "Cabinet",
        "brand": "Port & Bell",
    }
    compact = _compact_fields(fields, max_fields=10)
    keys = list(compact.keys())
    assert keys.index("label") < keys.index("plytix_product_id")
    assert keys.index("brand") < keys.index("plytix_product_id")
