# Generated by Django 4.2.9 on 2024-01-16 00:06

from django.db import migrations

from django.core.paginator import Paginator

def migrate_new_assigned_fields(apps, schema_editor):
    Result = apps.get_model('django_datawatch', 'Result')
    ResultAssignedGroup = apps.get_model('django_datawatch', 'ResultAssignedGroup')
    ResultAssignedUser = apps.get_model('django_datawatch', 'ResultAssignedUser')

    # Paginate the queryset to avoid memory issues
    paginator = Paginator(
        Result.objects.order_by('pk').only('assigned_to_user', 'assigned_to_group'),
        5000,
    )

    for page_number in paginator.page_range:
        page = paginator.page(page_number)
        group_instances = []
        user_instances = []

        for result in page.object_list:
            if result.assigned_to_group:
                group_instances.append(ResultAssignedGroup(
                    result_id=result.pk,
                    group_id=result.assigned_to_group.pk,
                ))
            if result.assigned_to_user:
                user_instances.append(ResultAssignedUser(
                    result_id=result.pk,
                    user_id=result.assigned_to_user.pk,
                ))

        ResultAssignedGroup.objects.bulk_create(group_instances)
        ResultAssignedUser.objects.bulk_create(user_instances)


class Migration(migrations.Migration):

    dependencies = [
        ('django_datawatch', '0004_resultassigneduser_resultassignedgroup_and_more'),
    ]

    operations = [
        migrations.RunPython(migrate_new_assigned_fields),
    ]
