# Generated by Django 6.0.1 on 2026-04-09

from django.db import migrations, models
from django.utils.crypto import get_random_string


TRANSACTION_CODE_PREFIX = "comal-"
TRANSACTION_CODE_LENGTH = 32
TRANSACTION_CODE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"


def populate_transaction_codes(apps, schema_editor):
    Order = apps.get_model("tienda", "Order")

    for order in Order.objects.filter(transaction_code__isnull=True):
        while True:
            code = f"{TRANSACTION_CODE_PREFIX}{get_random_string(TRANSACTION_CODE_LENGTH, TRANSACTION_CODE_ALPHABET)}"
            if not Order.objects.filter(transaction_code=code).exists():
                order.transaction_code = code
                order.save(update_fields=["transaction_code"])
                break


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("tienda", "0002_verificationcode_code_mode_and_more"),
    ]

    operations = [
        migrations.AddField(
            model_name="order",
            name="transaction_code",
            field=models.CharField(blank=True, db_index=True, max_length=38, null=True, unique=True),
        ),
        migrations.RunPython(populate_transaction_codes, noop_reverse),
    ]
