"""
Populate computed fields for hybrid filtering in rides.

This migration populates the opening_year and search_text fields that were added
in the previous migration. These fields enable efficient hybrid filtering by
pre-computing commonly filtered and searched data.
"""

import pghistory
from django.db import migrations


def populate_computed_fields(apps, schema_editor):
    """Populate computed fields for all existing rides."""
    Ride = apps.get_model("rides", "Ride")

    # Disable pghistory triggers during bulk operations to avoid performance issues
    with pghistory.context(disable=True):
        rides = list(
            Ride.objects.all().select_related(
                "park", "park__location", "park_area", "manufacturer", "designer", "ride_model"
            )
        )

        for ride in rides:
            # Extract opening year from opening_date
            if ride.opening_date:
                ride.opening_year = ride.opening_date.year
            else:
                ride.opening_year = None

            # Build comprehensive search text
            search_parts = []

            # Basic ride info
            if ride.name:
                search_parts.append(ride.name)
            if ride.description:
                search_parts.append(ride.description)

            # Park info
            if ride.park:
                search_parts.append(ride.park.name)
                if hasattr(ride.park, "location") and ride.park.location:
                    if ride.park.location.city:
                        search_parts.append(ride.park.location.city)
                    if ride.park.location.state:
                        search_parts.append(ride.park.location.state)
                    if ride.park.location.country:
                        search_parts.append(ride.park.location.country)

            # Park area
            if ride.park_area:
                search_parts.append(ride.park_area.name)

            # Category
            if ride.category:
                category_choices = [
                    ("", "Select ride type"),
                    ("RC", "Roller Coaster"),
                    ("DR", "Dark Ride"),
                    ("FR", "Flat Ride"),
                    ("WR", "Water Ride"),
                    ("TR", "Transport"),
                    ("OT", "Other"),
                ]
                category_display = dict(category_choices).get(ride.category, "")
                if category_display:
                    search_parts.append(category_display)

            # Status
            if ride.status:
                status_choices = [
                    ("", "Select status"),
                    ("OPERATING", "Operating"),
                    ("CLOSED_TEMP", "Temporarily Closed"),
                    ("SBNO", "Standing But Not Operating"),
                    ("CLOSING", "Closing"),
                    ("CLOSED_PERM", "Permanently Closed"),
                    ("UNDER_CONSTRUCTION", "Under Construction"),
                    ("DEMOLISHED", "Demolished"),
                    ("RELOCATED", "Relocated"),
                ]
                status_display = dict(status_choices).get(ride.status, "")
                if status_display:
                    search_parts.append(status_display)

            # Companies
            if ride.manufacturer:
                search_parts.append(ride.manufacturer.name)
            if ride.designer:
                search_parts.append(ride.designer.name)

            # Ride model
            if ride.ride_model:
                search_parts.append(ride.ride_model.name)
                if ride.ride_model.manufacturer:
                    search_parts.append(ride.ride_model.manufacturer.name)

            ride.search_text = " ".join(filter(None, search_parts)).lower()

        # Bulk update all rides
        Ride.objects.bulk_update(rides, ["opening_year", "search_text"], batch_size=1000)


def reverse_populate_computed_fields(apps, schema_editor):
    """Clear computed fields (reverse operation)."""
    Ride = apps.get_model("rides", "Ride")

    # Disable pghistory triggers during bulk operations
    with pghistory.context(disable=True):
        Ride.objects.all().update(opening_year=None, search_text="")


class Migration(migrations.Migration):
    dependencies = [
        ("rides", "0018_add_hybrid_filtering_fields"),
    ]

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