# Generated by Django 4.2.2 on 2024-04-07 23:27
from django.contrib.auth.hashers import make_password
from django.db import migrations
from phonenumber_field.phonenumber import PhoneNumber


def move_buyer_info_to_account(apps, schema_editor):
    Checklist = apps.get_model("store", "Checklist")
    User = apps.get_model("account", "User")

    # Normalize phone numbers first
    for order in Checklist.objects.all():
        if order.buyer_phone is None:
            continue

        old_phone = order.buyer_phone
        new_phone = PhoneNumber.from_string(order.buyer_phone, region="RU").as_e164
        if old_phone != new_phone:
            print(f"{old_phone} -> {new_phone}")
            order.buyer_phone = new_phone
            order.save(update_fields=['buyer_phone'])

    # Move buyer info to User
    for order in Checklist.objects.all():
        fields_to_copy = {
            'first_name': order.buyer_name,
            'telegram': order.buyer_telegram,
        }

        if order.buyer_phone is None:
            User.objects.create(**fields_to_copy)
            created = True
        else:
            obj, created = User.objects.update_or_create(phone=order.buyer_phone, defaults=fields_to_copy)

        if created:
            obj.is_draft_user = True
            obj.password = make_password(None)
            obj.save(update_fields=['password'])

        # Bind customer to order
        order.customer_id = obj.id
        order.save(update_fields=['customer_id'])


class Migration(migrations.Migration):
    dependencies = [
        ('account', '0010_bonusprogramtransaction_comment'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='bonusprogramtransaction',
            options={'ordering': ['-date']},
        ),
        migrations.RunPython(move_buyer_info_to_account, migrations.RunPython.noop),
    ]
