from app.jobs.set_collection_location_defaults import run_set_collection_location_defaults
from db.catalog_normalization_service import list_collection_commerce_profiles, upsert_collection_commerce_profile
from db.location_registry import ensure_default_home_surplus_locations
from db.models import MasterCollectionRegistry


def test_bulk_set_collection_location_defaults_updates_existing_and_creates_missing(catalog_intent_session):
    ensure_default_home_surplus_locations(catalog_intent_session)
    catalog_intent_session.add_all(
        [
            MasterCollectionRegistry(
                code="ACH",
                name="Anna Caramel Harvest",
                path_slug="kitchen-cabinets/anna-caramel-harvest",
                is_active=True,
            ),
            MasterCollectionRegistry(
                code="ASW",
                name="Anna Snow White",
                path_slug="kitchen-cabinets/anna-snow-white",
                is_active=True,
            ),
        ]
    )
    catalog_intent_session.flush()
    registry = catalog_intent_session.query(MasterCollectionRegistry).filter_by(code="ACH").one()
    upsert_collection_commerce_profile(
        catalog_intent_session,
        payload={
            "collection_registry_id": registry.id,
            "collection_name": "Anna Caramel Harvest",
            "category_l1": "Kitchen Cabinets",
            "channel_code": "magento",
            "connection_id": 4,
            "sample_master_sku": "ACH-SD",
            "default_location_code": "1",
        },
    )
    catalog_intent_session.commit()

    result = run_set_collection_location_defaults(
        channel_code="magento",
        connection_id=4,
        default_location_code="2",
        session=catalog_intent_session,
        apply=True,
    )

    assert result["updated_profile_count"] == 1
    assert result["created_profile_count"] == 1
    profiles = list_collection_commerce_profiles(catalog_intent_session, channel_code="magento", connection_id=4)["profiles"]
    by_name = {item["collection_name"]: item for item in profiles}
    assert by_name["Anna Caramel Harvest"]["default_location_code"] == "2"
    assert by_name["Anna Caramel Harvest"]["sample_master_sku"] == "ACH-SD"
    assert by_name["Anna Snow White"]["default_location_code"] == "2"
