# Generated by Django 4.2.23 on 2025-12-29 22:38

# Django
from django.db import migrations, models


def populate_order_references(apps, schema_editor):
    """Populate empty order_reference values with INDY-{id} format."""
    # Django
    from django.db import connection

    vendor = connection.vendor

    with connection.cursor() as cursor:
        if vendor == "mysql":
            # Populate sell orders with empty references (MySQL)
            cursor.execute(
                """
                UPDATE indy_hub_materialexchangesellorder
                SET order_reference = CONCAT('INDY-', id)
                WHERE order_reference = '' OR order_reference IS NULL
            """
            )

            # Populate buy orders with empty references (MySQL)
            cursor.execute(
                """
                UPDATE indy_hub_materialexchangebuyorder
                SET order_reference = CONCAT('INDY-', id)
                WHERE order_reference = '' OR order_reference IS NULL
            """
            )
        else:
            # Populate sell orders with empty references (SQLite/PostgreSQL)
            cursor.execute(
                """
                UPDATE indy_hub_materialexchangesellorder
                SET order_reference = 'INDY-' || id
                WHERE order_reference = '' OR order_reference IS NULL
            """
            )

            # Populate buy orders with empty references (SQLite/PostgreSQL)
            cursor.execute(
                """
                UPDATE indy_hub_materialexchangebuyorder
                SET order_reference = 'INDY-' || id
                WHERE order_reference = '' OR order_reference IS NULL
            """
            )


def reverse_populate_order_references(apps, schema_editor):
    """No-op for reverse."""
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("indy_hub", "0051_add_unique_constraints"),
    ]

    operations = [
        # Populate empty references
        migrations.RunPython(
            populate_order_references,
            reverse_populate_order_references,
        ),
        # Update field constraints - field already exists from 0049, just ensure constraints
        migrations.AlterField(
            model_name="materialexchangebuyorder",
            name="order_reference",
            field=models.CharField(
                blank=True,
                db_index=True,
                help_text="Unique order reference (INDY-{id}) for contract matching",
                max_length=50,
                unique=True,
            ),
        ),
        migrations.AlterField(
            model_name="materialexchangesellorder",
            name="order_reference",
            field=models.CharField(
                blank=True,
                db_index=True,
                help_text="Unique order reference (INDY-{id}) for contract matching",
                max_length=50,
                unique=True,
            ),
        ),
    ]
