"""Migration: make mobile the primary login identifier; make email optional."""

from django.db import migrations, models


def _fill_placeholder_mobile(apps, schema_editor):
    """Assign a unique placeholder mobile to any user that still has none."""
    User = apps.get_model("accounts", "User")
    for user in User.objects.filter(mobile__isnull=True):
        # Use a placeholder that is obviously synthetic and still unique.
        user.mobile = f"+000000{user.pk}"
        user.save(update_fields=["mobile"])


class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0003_mobile_and_auth_configs"),
    ]

    operations = [
        # 1. Back-fill any users with null mobile so the NOT NULL constraint can be applied.
        migrations.RunPython(_fill_placeholder_mobile, migrations.RunPython.noop),

        # 2. Make email optional (nullable).
        migrations.AlterField(
            model_name="user",
            name="email",
            field=models.EmailField(
                blank=True,
                db_index=True,
                max_length=254,
                null=True,
                unique=True,
                verbose_name="email address",
            ),
        ),

        # 3. Make mobile required (remove null / blank).
        migrations.AlterField(
            model_name="user",
            name="mobile",
            field=models.CharField(
                db_index=True,
                help_text="E.164 format, e.g. +989123456789",
                max_length=20,
                unique=True,
                verbose_name="mobile number",
            ),
        ),
    ]
