# Generated by Django 5.0.10 on 2025-01-10 18:28

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


def migrate_entry_objects(apps, schema_editor):
    Entry = apps.get_model("database", "Entry")
    FileObject = apps.get_model("database", "FileObject")
    db_alias = schema_editor.connection.alias

    # Process file objects in chunks
    chunk_size = 1000
    processed = 0
    processed_file_ids = set()

    while True:
        file_objects = list(
            FileObject.objects.using(db_alias)
            .exclude(id__in=processed_file_ids)
            .select_related("user")
            .only("id", "user", "file_name")[:chunk_size]
        )

        if not file_objects:
            break

        processed_file_ids.update([fo.id for fo in file_objects])

        for file_object in file_objects:
            try:
                # Find all entries matching this file object
                matching_entries = Entry.objects.using(db_alias).filter(
                    user_id=file_object.user_id, file_path=file_object.file_name, file_object__isnull=True
                )

                if matching_entries.exists():
                    # Update all matching entries in bulk
                    matching_entries.update(file_object=file_object)
            except Exception as e:
                print(f"Error processing file object {file_object.id}: {str(e)}")
                continue

        processed += len(file_objects)
        print(f"Processed {processed} file objects")


def reverse_migration(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("database", "0078_khojuser_email_verification_code_expiry"),
    ]

    operations = [
        migrations.AddField(
            model_name="entry",
            name="file_object",
            field=models.ForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="database.fileobject",
            ),
        ),
        migrations.RunPython(migrate_entry_objects, reverse_migration),
    ]
