# Generated by Django 5.1.3 on 2024-12-02 10:58

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


def init_profile_contact(apps, schema_editor):
    """Create a Contact for each User to be used as their profile."""
    User = apps.get_model("core", "User")
    Contact = apps.get_model("core", "Contact")

    for user in User.objects.all():  # This is a small table for now
        Contact.objects.create(
            owner=user,
            user=user,
            full_name=user.name or user.email,
            data={
                "emails": [
                    {"type": "Work", "value": user.email},
                ],
            },
        )


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0007_rename_contact_base_to_override'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='user',
            name='profile_contact',
        ),
        migrations.AddField(
            model_name='contact',
            name='user',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='profile_contact', to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddConstraint(
            model_name='contact',
            constraint=models.CheckConstraint(condition=models.Q(('user__isnull', True), models.Q(('owner', models.F('user')), ('owner__isnull', False)), _connector='OR'), name='profile_contact_owner_constraint', violation_error_message='Users can only declare as profile a contact they own.'),
        ),
        migrations.RunPython(init_profile_contact, reverse_code=migrations.RunPython.noop),
    ]
