# Generated by Django 3.0.6 on 2020-06-17 10:43

from logging import getLogger

from django.db import migrations
from django.db.models import Exists, OuterRef

logger = getLogger(__name__)


def copy_contacts(apps, schema_editor):
    """Copies contact to contacts."""
    pipeline_model = apps.get_model('company_list', 'PipelineItem')
    no_contacts_subquery = Exists(
        pipeline_model.objects.filter(
            pk=OuterRef('pk'),
            contacts__id__isnull=True,
        ).only(
            'pk',
        )
    )
    items_with_uncopied_contacts = pipeline_model.objects.select_for_update().annotate(
        has_no_contacts=no_contacts_subquery,
    ).filter(
        contact__isnull=False,
        has_no_contacts=True,
    ).only(
        'pk',
        'contact',
    )

    num_updated = 0

    for item in items_with_uncopied_contacts:
        item.contacts.add(item.contact)
        num_updated += 1

    logger.info(
        f'PipelineItem.contact copied to PipelineItem.contacts for {num_updated} items',
    )


class Migration(migrations.Migration):

    dependencies = [
        ('company_list', '0018_add_multiple_contacts_to_piplelineitem'),
    ]

    operations = [
        migrations.RunPython(copy_contacts, migrations.RunPython.noop, elidable=True),
    ]
