# Generated by Django 5.2.5 on 2025-08-27 22:02
import logging

from django.db import migrations
from django.db import models

from documents.templating.utils import convert_format_str_to_template_format

logger = logging.getLogger("paperless.migrations")


def convert_from_format_to_template(apps, schema_editor):
    WorkflowAction = apps.get_model("documents", "WorkflowAction")

    batch_size = 500
    actions_to_update = []

    queryset = (
        WorkflowAction.objects.filter(assign_title__isnull=False)
        .exclude(assign_title="")
        .only("id", "assign_title")
    )

    for action in queryset:
        action.assign_title = convert_format_str_to_template_format(
            action.assign_title,
        )
        logger.debug(
            "Converted WorkflowAction id %d title to template format: %s",
            action.id,
            action.assign_title,
        )
        actions_to_update.append(action)

    if actions_to_update:
        WorkflowAction.objects.bulk_update(
            actions_to_update,
            ["assign_title"],
            batch_size=batch_size,
        )


class Migration(migrations.Migration):
    dependencies = [
        ("documents", "1072_workflowtrigger_filter_custom_field_query_and_more"),
    ]

    operations = [
        migrations.AlterField(
            model_name="workflowaction",
            name="assign_title",
            field=models.TextField(
                blank=True,
                help_text="Assign a document title, must  be a Jinja2 template, see documentation.",
                null=True,
                verbose_name="assign title",
            ),
        ),
        migrations.RunPython(
            convert_from_format_to_template,
            migrations.RunPython.noop,
        ),
    ]
