"""Data migration: auto-detect mobile_country for existing users from their E.164 mobile."""
from django.db import migrations


def populate_mobile_country(apps, schema_editor):
    """Match each user's mobile prefix to the longest known dial_code."""
    User = apps.get_model("accounts", "User")
    Country = apps.get_model("localization", "Country")

    countries = sorted(
        Country.objects.filter(is_enabled=True),
        key=lambda c: len(c.dial_code),
        reverse=True,  # match longer prefixes first (e.g. +1868 before +1)
    )
    if not countries:
        return

    for user in User.objects.filter(mobile_country__isnull=True, mobile__startswith="+"):
        for country in countries:
            if user.mobile.startswith(country.dial_code):
                user.mobile_country = country
                user.save(update_fields=["mobile_country"])
                break


def reverse_populate(apps, schema_editor):
    pass  # non-destructive; no need to undo


class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0007_user_mobile_country_fk"),
        ("localization", "0003_add_timezone_model"),
    ]

    operations = [
        migrations.RunPython(populate_mobile_country, reverse_populate),
    ]
