from django.db import migrations


def drop_stock_non_negative_constraint(apps, schema_editor):
    """Supprime la contrainte MySQL historique, sans effet sur SQLite/tests."""

    if schema_editor.connection.vendor != "mysql":
        return

    with schema_editor.connection.cursor() as cursor:
        cursor.execute(
            """
            SELECT COUNT(*)
            FROM information_schema.TABLE_CONSTRAINTS
            WHERE CONSTRAINT_SCHEMA = DATABASE()
              AND TABLE_NAME = 'facturation_stockpointdevente'
              AND CONSTRAINT_NAME = 'stock_quantite_gte_0'
            """
        )
        constraint_exists = bool(cursor.fetchone()[0])

    if constraint_exists:
        schema_editor.execute(
            "ALTER TABLE facturation_stockpointdevente DROP CHECK stock_quantite_gte_0"
        )


def restore_stock_non_negative_constraint(apps, schema_editor):
    """Restaure la contrainte sur MySQL lors d'un rollback."""

    if schema_editor.connection.vendor != "mysql":
        return

    with schema_editor.connection.cursor() as cursor:
        cursor.execute(
            """
            SELECT COUNT(*)
            FROM information_schema.TABLE_CONSTRAINTS
            WHERE CONSTRAINT_SCHEMA = DATABASE()
              AND TABLE_NAME = 'facturation_stockpointdevente'
              AND CONSTRAINT_NAME = 'stock_quantite_gte_0'
            """
        )
        constraint_exists = bool(cursor.fetchone()[0])

    if not constraint_exists:
        schema_editor.execute(
            "ALTER TABLE facturation_stockpointdevente "
            "ADD CONSTRAINT stock_quantite_gte_0 CHECK (quantite >= 0)"
        )


class Migration(migrations.Migration):

    dependencies = [
        ("facturation", "0033_produit_code_barres"),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            database_operations=[
                migrations.RunPython(
                    drop_stock_non_negative_constraint,
                    reverse_code=restore_stock_non_negative_constraint,
                ),
            ],
            state_operations=[
                migrations.RemoveConstraint(
                    model_name="stockpointdevente",
                    name="stock_quantite_gte_0",
                ),
            ],
        ),
    ]
