# Generated by Django 5.2.5 on 2025-09-14 19:01

from django.db import migrations


def populate_computed_fields(apps, schema_editor):
    """Populate computed fields for existing parks using raw SQL with disabled triggers"""

    # Temporarily disable pghistory triggers
    schema_editor.execute("ALTER TABLE parks_park DISABLE TRIGGER ALL;")

    try:
        # Use raw SQL to update opening_year from opening_date
        schema_editor.execute(
            """
            UPDATE parks_park
            SET opening_year = EXTRACT(YEAR FROM opening_date)
            WHERE opening_date IS NOT NULL;
        """
        )

        # Use raw SQL to populate search_text
        # This is a simplified version - we'll populate it with just name and description
        schema_editor.execute(
            """
            UPDATE parks_park
            SET search_text = LOWER(
                COALESCE(name, '') || ' ' ||
                COALESCE(description, '')
            );
        """
        )

        # Update search_text to include operator names using a join
        schema_editor.execute(
            """
            UPDATE parks_park
            SET search_text = LOWER(
                COALESCE(parks_park.name, '') || ' ' ||
                COALESCE(parks_park.description, '') || ' ' ||
                COALESCE(parks_company.name, '')
            )
            FROM parks_company
            WHERE parks_park.operator_id = parks_company.id;
        """
        )

    finally:
        # Re-enable pghistory triggers
        schema_editor.execute("ALTER TABLE parks_park ENABLE TRIGGER ALL;")


def reverse_populate_computed_fields(apps, schema_editor):
    """Clear computed fields (reverse operation)"""
    Park = apps.get_model("parks", "Park")
    Park.objects.update(opening_year=None, search_text="")


class Migration(migrations.Migration):

    dependencies = [
        ("parks", "0014_add_hybrid_filtering_fields"),
    ]

    operations = [
        migrations.RunPython(
            populate_computed_fields,
            reverse_populate_computed_fields,
        ),
    ]
