# Generated by Django 4.2.20 on 2025-11-02 18:56

from collections import defaultdict

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


def _clean_email(value):
    if not value:
        return ''
    return value.strip().lower()


def link_contacts_to_users(apps, schema_editor):
    Contact = apps.get_model('unicrm', 'Contact')
    app_label, model_name = settings.AUTH_USER_MODEL.split('.')
    UserModel = apps.get_model(app_label, model_name)

    contacts = Contact.objects.filter(attributes__auth_user_id__isnull=False).order_by('pk')
    candidates: dict[int, list] = defaultdict(list)
    for contact in contacts:
        attributes = contact.attributes or {}
        raw_user_id = attributes.get('auth_user_id')
        try:
            user_id = int(raw_user_id)
        except (TypeError, ValueError):
            continue
        candidates[user_id].append(contact)

    if not candidates:
        return

    users = UserModel.objects.filter(pk__in=candidates.keys())
    user_map = {user.pk: user for user in users}

    for user_id, contact_list in candidates.items():
        user = user_map.get(user_id)
        if user is None:
            continue

        user_email = _clean_email(getattr(user, 'email', ''))
        selected_contact = None

        for contact in contact_list:
            contact_email = _clean_email(contact.email)
            if user_email and contact_email == user_email:
                selected_contact = contact
                break

        if selected_contact is None:
            for contact in contact_list:
                if _clean_email(contact.email):
                    selected_contact = contact
                    break

        if selected_contact is None:
            selected_contact = contact_list[0]

        if selected_contact.user_id == user.pk:
            continue

        selected_contact.user_id = user.pk
        selected_contact.save(update_fields=['user', 'updated_at'])


def unlink_contacts_from_users(apps, schema_editor):
    Contact = apps.get_model('unicrm', 'Contact')
    Contact.objects.filter(user__isnull=False).update(user=None)


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('unicrm', '0004_alter_contact_email'),
    ]

    operations = [
        migrations.AddField(
            model_name='contact',
            name='user',
            field=models.OneToOneField(blank=True, help_text='Linked Django auth user for this contact, when applicable.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='crm_contact', to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterField(
            model_name='communication',
            name='status_summary',
            field=models.JSONField(blank=True, default=dict, help_text='Aggregated counters for linked messages (e.g. sent, opened, clicked, failed).', verbose_name='Status summary'),
        ),
        migrations.RunPython(link_contacts_to_users, unlink_contacts_from_users),
    ]
