# Generated by Django 4.2.11 on 2024-05-24 16:22
import logging

from django.db import migrations, models
import django_migration_linter as linter

logger = logging.getLogger(__name__)


def clean_up_duplicated_teams(apps, schema_editor):
    Team = apps.get_model("user_management", "Team")
    User = apps.get_model("user_management", "User")

    # get (organization_id, team_id) pairs for duplicated teams
    duplicate_rows = Team.objects.values_list(
        "organization_id", "team_id"
    ).annotate(count=models.Count("id")).filter(count__gt=1)

    for organization_id, team_id, _ in duplicate_rows:
        # keep first team
        first_team = Team.objects.filter(
            organization_id=organization_id,
            team_id=team_id,
        ).order_by("id").first()

        # migrate resources associated to duplicated entries
        duplicated_teams = Team.objects.filter(
            organization_id=organization_id,
            team_id=team_id,
        ).exclude(id=first_team.id)

        for team in duplicated_teams:
            # if there is anything to migrate, do it here
            team.escalation_chains.update(team=first_team)
            # remove direct paging integrations before removing teams
            team.alert_receive_channels.filter(integration="direct_paging").delete()
            team.alert_receive_channels.update(team=first_team)
            team.custom_on_call_shifts.update(team=first_team)
            team.oncall_schedules.update(team=first_team)
            team.webhooks.update(team=first_team)
            User.objects.filter(organization_id=organization_id, current_team=team).update(current_team=first_team)

        # delete duplicated teams
        num_deleted, _ = duplicated_teams.delete()
        logger.info(
            f"Deleted {num_deleted} duplicate teams for ({organization_id}, {team_id}), "
            f"keeping team with id: {first_team.id}."
        )


class Migration(migrations.Migration):

    dependencies = [
        ('user_management', '0021_user_google_calendar_settings'),
    ]

    operations = [
        linter.IgnoreMigration(), # removing duplicated teams is ok, no way to revert this
        migrations.RunPython(clean_up_duplicated_teams, migrations.RunPython.noop),
        migrations.AlterUniqueTogether(
            name='team',
            unique_together={('organization', 'team_id')},
        ),
    ]
