# Generated by Django 2.2.24 on 2021-07-01 10:45

from django.db import migrations

from intranet.femida.src.candidates.choices import CONTACT_TYPES
from intranet.femida.src.candidates.contacts import normalize_contact_url
from intranet.femida.src.utils.queryset import queryset_iterator


def update_normalized_account_id(apps, schema_editor):
    CandidateContact = apps.get_model('candidates', 'CandidateContact')
    contacts = queryset_iterator(
        queryset=CandidateContact.objects.filter(type=CONTACT_TYPES.linkedin),
        chunk_size=10000,
    )
    contacts_to_update = []
    for contact in contacts:
        normalized = normalize_contact_url(CONTACT_TYPES.linkedin, contact.account_id)
        if normalized and normalized != contact.normalized_account_id:
            contact.normalized_account_id = normalized
            contacts_to_update.append(contact)

    CandidateContact.objects.bulk_update(
        contacts_to_update,
        ['normalized_account_id'],
        batch_size=1000,
    )


class Migration(migrations.Migration):

    dependencies = [
        ('candidates', '0028_submission_publication_url_max_length'),
    ]

    operations = [
        migrations.RunPython(
            code=update_normalized_account_id,
            reverse_code=lambda *x, **y: None,
        )
    ]
