from unittest.mock import patch

from db.master_static_field_mapping import CREATE_NEW_MARKER, save_static_field_mappings_batch


def test_save_batch_reports_pending_create_channels():
    rows = [
        {
            "master_attribute_code": "door_style",
            "shopify": CREATE_NEW_MARKER,
            "magento": CREATE_NEW_MARKER,
        }
    ]

    class FakeSession:
        pass

    session = FakeSession()
    with patch("db.master_static_field_mapping.upsert_static_field_mappings", return_value=1):
        with patch("db.master_static_field_mapping.sync_static_mappings_to_channel_aliases", return_value=2):
            stats = save_static_field_mappings_batch(session, rows, sync_aliases=True)

    assert stats["upserted"] == 1
    assert stats["aliases_synced"] == 2
    assert set(stats["pending_create_channels"]) == {"magento", "shopify"}


def test_provision_pending_for_channels_skips_without_connection():
    from db.channel_attribute_provision import provision_pending_for_channels

    class FakeSession:
        pass

    result = provision_pending_for_channels(
        FakeSession(),
        ["magento", "shopify"],
        magento_connection_id=None,
        shopify_connection_id=None,
    )
    assert result["magento"]["status"] == "skipped"
    assert result["shopify"]["status"] == "skipped"


def test_shopify_attribute_namespace_defaults_to_custom_for_underscored_codes():
    from db.channel_attribute_provision import _shopify_namespace_key

    assert _shopify_namespace_key("l_shape_layout_price") == ("custom", "l_shape_layout_price")
    assert _shopify_namespace_key("cabinet_door_style") == ("custom", "cabinet_door_style")
    assert _shopify_namespace_key("custom_layout_price") == ("custom", "layout_price")


def test_magento_create_options_are_conservative_for_text_attributes():
    from db.channel_attribute_provision import _magento_create_options

    options = _magento_create_options("text")
    assert options["is_filterable"] is False
    assert options["is_filterable_in_search"] is False
    assert options["is_searchable"] is False
