# Generated by Django 5.2.9 on 2026-01-12 12:23

from django.db import migrations, models
from tqdm import tqdm


def cleanup_duplicates(apps, schema_editor):
    EmailContact = apps.get_model("directory", "EmailContact")
    qs = EmailContact.objects.values("address").annotate(c=models.Count("*")).filter(c__gt=1).values("address")
    for rel in tqdm(qs, total=qs.count()):
        a = rel["address"]

        qs = EmailContact.objects.filter(address=a)
        # delete inactive contacts
        qs.filter(models.Q(entry__isnull=True) | models.Q(entry__is_active=False)).delete()

        # delete contact linked to company if it is already linked to person
        if qs.filter(entry__entry_type="Person").exists() and qs.filter(entry__entry_type="Company").exists():
            qs.filter(entry__entry_type="Company").delete()

        # for each duplicates, try to merge it, otherwise delete the email address
        if qs.count() > 1:
            first_contact = qs.earliest("entry_id")
            for tt in qs.exclude(id=first_contact.id):
                tt.delete()


class Migration(migrations.Migration):

    dependencies = [
        ('directory', '0014_alter_entry_relationship_managers_and_more'),
    ]

    operations = [
        migrations.RunSQL(sql="SET CONSTRAINTS ALL IMMEDIATE;"),
        migrations.RunPython(cleanup_duplicates),
        migrations.RunSQL(sql="SET CONSTRAINTS ALL DEFERRED;"),
        migrations.AlterField(
            model_name='emailcontact',
            name='address',
            field=models.EmailField(max_length=254, unique=True, verbose_name='Email Address'),
        ),
        migrations.AddConstraint(
            model_name='emailcontact',
            constraint=models.UniqueConstraint(condition=models.Q(('primary', True)), fields=('entry',), name='unique_primary_entry_address'),
        ),
    ]
