# Generated by Django 5.1.7 on 2025-04-04 01:08


import datetime

from django.db import migrations
from django.db import models
from django.utils.timezone import localtime


def migrate_date(apps, schema_editor):
    Document = apps.get_model("documents", "Document")

    # Batch to avoid loading all objects into memory at once,
    # which would be problematic for large datasets.
    batch_size = 500
    updates = []
    total_updated = 0
    total_checked = 0

    for doc in Document.objects.only("id", "created").iterator(chunk_size=batch_size):
        total_checked += 1
        if doc.created:
            doc.created_date = localtime(doc.created).date()
            updates.append(doc)

        if len(updates) >= batch_size:
            Document.objects.bulk_update(updates, ["created_date"])
            total_updated += len(updates)
            print(
                f"[1067_alter_document_created] {total_updated} of {total_checked} processed...",
            )
            updates.clear()

    if updates:
        Document.objects.bulk_update(updates, ["created_date"])
        total_updated += len(updates)
        print(
            f"[1067_alter_document_created] {total_updated} of {total_checked} processed...",
        )

    if total_checked > 0:
        print(f"[1067_alter_document_created] completed for {total_checked} documents.")


class Migration(migrations.Migration):
    dependencies = [
        ("documents", "1066_alter_workflowtrigger_schedule_offset_days"),
    ]

    operations = [
        migrations.AddField(
            model_name="document",
            name="created_date",
            field=models.DateField(null=True),
        ),
        migrations.RunPython(migrate_date, reverse_code=migrations.RunPython.noop),
        migrations.RemoveField(
            model_name="document",
            name="created",
        ),
        migrations.RenameField(
            model_name="document",
            old_name="created_date",
            new_name="created",
        ),
        migrations.AlterField(
            model_name="document",
            name="created",
            field=models.DateField(
                db_index=True,
                default=datetime.datetime.today,
                verbose_name="created",
            ),
        ),
    ]
