# Generated by Django 4.2.17 on 2025-01-06 15:48

import logging

from django.db import migrations
from django.db.models import Subquery, OuterRef

logger = logging.getLogger(__name__)


def update_direct_paging_integration_non_default_routes(apps, schema_editor):
    """
    If any of the original Direct Paging integration default routes had chatops settings or escalation chains
    associated with them, simply set the non-default route to have the same settings. This will avoid any functional
    differences should users start paging a team using the "important" functionality.
    """
    ChannelFilter = apps.get_model("alerts", "ChannelFilter")

    logger.info("Starting update_direct_paging_integration_non_default_routes migration...")

    # 1) Gather all default route data in a dictionary keyed by alert_receive_channel_id
    default_direct_paging_routes = ChannelFilter.objects.filter(
        alert_receive_channel__integration="direct_paging",
        is_default=True
    ).values(
        "alert_receive_channel_id",
        "escalation_chain_id",
        "telegram_channel_id",
        "notify_in_telegram",
        "slack_channel_id",
        "notify_in_slack",
        "notification_backends",
    )

    default_direct_paging_route_map = {
        route["alert_receive_channel_id"]: route for route in default_direct_paging_routes
    }

    # 2) Fetch all non-default direct paging routes we want to update
    non_default_direct_paging_routes = list(ChannelFilter.objects.filter(
        alert_receive_channel__integration="direct_paging",
        is_default=False
    ))

    # 3) Update them in Python memory
    for non_default_route in non_default_direct_paging_routes:
        default_route = default_direct_paging_route_map.get(non_default_route.alert_receive_channel_id)
        if default_route:
            non_default_route.escalation_chain_id = default_route["escalation_chain_id"]
            non_default_route.telegram_channel_id = default_route["telegram_channel_id"]
            non_default_route.notify_in_telegram = default_route["notify_in_telegram"]
            non_default_route.slack_channel_id = default_route["slack_channel_id"]
            non_default_route.notify_in_slack = default_route["notify_in_slack"]
            non_default_route.notification_backends = default_route["notification_backends"]

    # 4) Bulk update all at once
    ChannelFilter.objects.bulk_update(
        non_default_direct_paging_routes,
        [
            "escalation_chain_id",
            "telegram_channel_id",
            "notify_in_telegram",
            "slack_channel_id",
            "notify_in_slack",
            "notification_backends",
        ],
        batch_size=5000,
    )

    logger.info(f"Updated {len(non_default_direct_paging_routes)} non-default direct paging integration routes")
    logger.info("Finished update_direct_paging_integration_non_default_routes migration.")


class Migration(migrations.Migration):

    dependencies = [
        ("alerts", "0072_upsert_direct_paging_integration_routes"),
    ]

    operations = [
        migrations.RunPython(update_direct_paging_integration_non_default_routes, migrations.RunPython.noop),
    ]
