# Generated by Django 5.2.4 on 2025-09-17 16:40

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


def migrate_user_phone_numbers(apps, schema_editor):
    User = apps.get_model("core", "User")
    Phone = apps.get_model("core", "UserPhoneNumber")
    db_alias = schema_editor.connection.alias

    phones_to_create = []
    users = (
        User.objects.using(db_alias)
        .exclude(phone_number__isnull=True)
        .exclude(phone_number="")
    )
    for user in users.iterator():
        phones_to_create.append(
            Phone(user_id=user.pk, number=user.phone_number, priority=0)
        )

    if phones_to_create:
        Phone.objects.using(db_alias).bulk_create(phones_to_create)


def revert_user_phone_numbers(apps, schema_editor):
    User = apps.get_model("core", "User")
    Phone = apps.get_model("core", "UserPhoneNumber")
    db_alias = schema_editor.connection.alias

    for user in User.objects.using(db_alias).all():
        number = (
            Phone.objects.using(db_alias)
            .filter(user_id=user.pk)
            .order_by("priority", "id")
            .values_list("number", flat=True)
            .first()
        )
        if number:
            User.objects.using(db_alias).filter(pk=user.pk).update(phone_number=number)


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0025_remove_user_has_charger"),
    ]

    operations = [
        migrations.CreateModel(
            name="UserPhoneNumber",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "number",
                    models.CharField(help_text="Contact phone number", max_length=20),
                ),
                ("priority", models.PositiveIntegerField(default=0)),
                (
                    "user",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="phone_numbers",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
            options={
                "verbose_name": "Phone Number",
                "verbose_name_plural": "Phone Numbers",
                "ordering": ("priority", "id"),
            },
        ),
        migrations.RunPython(migrate_user_phone_numbers, revert_user_phone_numbers),
        migrations.RemoveField(
            model_name="user",
            name="phone_number",
        ),
    ]
