# Generated by Django 3.1.14 on 2024-08-19 14:56

from django.db import (
    migrations,
)

from edu_rdm_integration.enums import (
    FileUploadStatusEnum,
)
from educommon.utils.seqtools import (
    make_chunks,
)


# Значение размера файла по умолчанию (если файл не найден)
ATTACHMENT_SIZES = 10_485_760
CHUNK_SIZE = 500


def set_attachment_size(apps, schema_editor):
    """Установка размера файла по умолчанию."""
    ExportingDataSubStageAttachment = apps.get_model(
        'edu_rdm_integration', 'ExportingDataSubStageAttachment'
    )  # noqa: N806
    ExportingDataSubStageUploaderClientLog = apps.get_model(
        'edu_rdm_integration', 'ExportingDataSubStageUploaderClientLog'
    )  # noqa: N806

    attachment_ids = ExportingDataSubStageUploaderClientLog.objects.filter(
        file_upload_status=FileUploadStatusEnum.IN_PROGRESS
    ).values_list('attachment_id', flat=True).iterator()

    sub_stage_with_deleted_attachments = []
    for chunked_attachment_ids in make_chunks(attachment_ids, CHUNK_SIZE):
        for sub_stage_attachment in ExportingDataSubStageAttachment.objects.filter(
            attachment_size__isnull=True,
            id__in=chunked_attachment_ids,
        ):
            if sub_stage_attachment.attachment.field.storage.exists(sub_stage_attachment.attachment.name):
                sub_stage_attachment.attachment_size = sub_stage_attachment.attachment.size
            else:
                sub_stage_attachment.attachment_size = ATTACHMENT_SIZES
            sub_stage_with_deleted_attachments.append(sub_stage_attachment)

        ExportingDataSubStageAttachment.objects.bulk_update(sub_stage_with_deleted_attachments, ['attachment_size'])


class Migration(migrations.Migration):

    dependencies = [
        ('edu_rdm_integration', '0012_exportingdatasubstageattachment_attachment_size'),
    ]

    operations = [
        migrations.RunPython(set_attachment_size, reverse_code=migrations.RunPython.noop)
    ]

