# Generated by Django 4.2.23 on 2026-02-27 00:00

from django.db import migrations, models


def add_compliance_filter_column_if_missing(apps_registry, schema_editor):
    """
    Ensure the compliance_filter_id column exists regardless of charlink install.
    """
    table_name = "aa_bb_tickettoolconfig"
    column_name = "compliance_filter_id"

    try:
        with schema_editor.connection.cursor() as cursor:
            columns = [
                col.name
                for col in schema_editor.connection.introspection.get_table_description(
                    cursor, table_name
                )
            ]
    except Exception:
        # If the table isn't present yet or introspection fails, bail out.
        return

    if column_name in columns:
        return

    vendor = schema_editor.connection.vendor
    if vendor == "sqlite":
        column_type = "integer"
    elif vendor in ("postgresql", "mysql"):
        column_type = "bigint"
    else:
        column_type = "bigint"

    qn = schema_editor.quote_name
    schema_editor.execute(
        f"ALTER TABLE {qn(table_name)} ADD COLUMN {qn(column_name)} {column_type} NULL"
    )


def reverse_noop(apps_registry, schema_editor):
    # No-op: we do not want to drop the column.
    pass


class Migration(migrations.Migration):

    atomic = False

    dependencies = [
        ("aa_bb", "0117_tickettoolconfig_compliance_filter_column"),
    ]

    operations = [
        migrations.RunPython(add_compliance_filter_column_if_missing, reverse_noop),
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.AddField(
                    model_name="tickettoolconfig",
                    name="compliance_filter_id",
                    field=models.BigIntegerField(
                        blank=True,
                        null=True,
                        help_text="Select your compliance filter (charlink).",
                    ),
                ),
            ],
            database_operations=[],
        ),
    ]
