# Generated by Django 6.0.2 on 2026-02-05 06:50

import uuid

from django.db import migrations


class Migration(migrations.Migration):
    dependencies = [
        ("sandwitches", "0019_order_tracking_token"),
    ]

    # Re-implementing the logic directly within RunPython for self-containment:

    def populate_unique_tokens(apps, schema_editor):
        Order = apps.get_model("sandwitches", "Order")  # ty:ignore[unresolved-attribute]

        # Get all orders that have a tracking token (if any)

        orders_with_tokens = Order.objects.exclude(tracking_token=None)

        # Find tokens that appear more than once

        duplicate_token_groups = {}

        for order in orders_with_tokens:
            token_str = str(order.tracking_token)  # Ensure we compare strings

            if token_str not in duplicate_token_groups:
                duplicate_token_groups[token_str] = []

            duplicate_token_groups[token_str].append(order)

        # Update duplicate tokens to be unique

        for token_str, order_group in duplicate_token_groups.items():
            if len(order_group) > 1:
                # Keep the first order's token

                # For subsequent orders, generate a new unique token

                for order_to_update in order_group[1:]:
                    new_token = uuid.uuid4()

                    # Ensure the new token is truly unique across all existing orders (not just within this group)

                    while Order.objects.filter(tracking_token=new_token).exists():
                        new_token = uuid.uuid4()

                    order_to_update.tracking_token = new_token

                    order_to_update.save()

    operations = [
        migrations.RunPython(
            populate_unique_tokens,
            migrations.RunPython.noop,
        ),
    ]
