# Generated by Django 4.2.7 on 2023-11-28 10:45
import logging

from django.db import migrations, models
from django.utils import timezone

logger = logging.getLogger(__name__)


def delete_duplicate_direct_paging_integrations(apps, schema_editor):
    AlertReceiveChannel = apps.get_model("alerts", "AlertReceiveChannel")

    # get (organization_id, team_id) pairs for teams that have more than one direct paging integration
    duplicate_rows = AlertReceiveChannel.objects.values_list(
        "organization_id", "team_id"
    ).annotate(count=models.Count("id")).filter(integration="direct_paging", deleted_at__isnull=True, count__gt=1)

    for organization_id, team_id, _ in duplicate_rows:
        # get the first direct paging integration for the team (the one we want to keep)
        first_direct_paging_integration = AlertReceiveChannel.objects.filter(
            organization_id=organization_id,
            team_id=team_id,
            integration="direct_paging",
            deleted_at__isnull=True,
        ).order_by("id").first()

        if first_direct_paging_integration is None:
            continue

        # delete all other direct paging integrations for the team (except the first one)
        num_deleted = AlertReceiveChannel.objects.filter(
            organization_id=organization_id,
            team_id=team_id,
            integration="direct_paging",
            deleted_at__isnull=True,
        ).exclude(id=first_direct_paging_integration.id).update(deleted_at=timezone.now())

        logger.info(
            f"Deleted {num_deleted} duplicate direct paging integrations for team ({organization_id}, {team_id}), "
            f"keeping only one direct paging integration for team: {first_direct_paging_integration.id}."
        )


class Migration(migrations.Migration):

    dependencies = [
        ('alerts', '0040_alertreceivechannel_alert_group_labels_custom_and_more'),
    ]

    operations = [
        migrations.RunPython(delete_duplicate_direct_paging_integrations, migrations.RunPython.noop),
        migrations.AddConstraint(
            model_name='alertreceivechannel',
            constraint=models.UniqueConstraint(models.F('organization'), models.Case(models.When(team=None, then=0), default=models.F('team'), output_field=models.BigIntegerField()), models.Case(models.When(deleted_at__isnull=True, then=True), default=None), models.Case(models.When(integration='direct_paging', then=True), default=None), name='unique_direct_paging_integration_per_team'),
        ),
    ]
