from django.db import migrations

from apps.core.countries import ALL_COUNTRY_MAP, to_country_name

# (model, JSONField holding a list of country values)
_SPECS = [
    ("BuyerRegistryEntry", "geographic_coverage"),
    ("ProductListing", "geographic_reach"),
    ("MarketDemandListing", "geographic_targeting"),
]


def _convert(apps, mapper):
    for model_name, field in _SPECS:
        Model = apps.get_model("smehub_marketplace", model_name)
        for obj in Model.objects.iterator():
            vals = getattr(obj, field) or []
            if not isinstance(vals, list) or not vals:
                continue
            new = [m for m in (mapper(v) for v in vals) if m]
            if new != vals:
                Model.objects.filter(pk=obj.pk).update(**{field: new})


def _forwards(apps, schema_editor):
    _convert(apps, lambda v: to_country_name(v))


def _backwards(apps, schema_editor):
    name_to_code = {name: code for code, name in ALL_COUNTRY_MAP.items()}
    _convert(apps, lambda v: name_to_code.get(v, v))


class Migration(migrations.Migration):

    dependencies = [
        ("smehub_marketplace", "0004_slice_c_search_indexes"),
    ]

    operations = [
        migrations.RunPython(_forwards, _backwards),
    ]
