# Generated by Django 4.2.15 on 2024-11-12 09:33
import logging

from django.db import migrations
import django_migration_linter as linter

logger = logging.getLogger(__name__)


def migrate_static_labels(apps, schema_editor):
    AlertReceiveChannelAssociatedLabel = apps.get_model("labels", "AlertReceiveChannelAssociatedLabel")
    AlertReceiveChannel = apps.get_model("alerts", "AlertReceiveChannel")

    logging.info("Start migrating alert group static labels to integration labels")

    labels_associations_to_create = []
    alert_receive_channels_to_update = []

    alert_receive_channels = AlertReceiveChannel.objects.filter(alert_group_labels_custom__isnull=False)
    logging.info(f"Found {alert_receive_channels.count()} integrations with custom alert groups labels")
    for alert_receive_channel in alert_receive_channels:
        update_labels = False
        labels = alert_receive_channel.alert_group_labels_custom[:]
        for label in labels:
            if label[1] is not None:
                labels_associations_to_create.append(
                    AlertReceiveChannelAssociatedLabel(
                        key_id=label[0],
                        value_id=label[1],
                        organization=alert_receive_channel.organization,
                        alert_receive_channel=alert_receive_channel
                    )
                )
                alert_receive_channel.alert_group_labels_custom.remove(label)
                update_labels = True
        if update_labels:
            alert_receive_channels_to_update.append(alert_receive_channel)

    AlertReceiveChannelAssociatedLabel.objects.bulk_create(
        labels_associations_to_create, ignore_conflicts=True, batch_size=5000
    )
    logging.info("Bulk created label associations")
    AlertReceiveChannel.objects.bulk_update(alert_receive_channels_to_update, fields=["alert_group_labels_custom"], batch_size=5000)
    logging.info("Bulk updated integrations")
    logging.info("Finished migrating static labels to integration labels")


class Migration(migrations.Migration):

    dependencies = [
        ('alerts', '0070_remove_resolutionnoteslackmessage__slack_channel_id_db'),
        ('labels', '0005_labelkeycache_prescribed_labelvaluecache_prescribed'),
    ]

    operations = [
        # migrate static alert group labels to integration labels
        linter.IgnoreMigration(),
        migrations.RunPython(migrate_static_labels, migrations.RunPython.noop),
    ]
