# Generated by Django 4.2.10 on 2024-04-15 18:44

import hashlib

from django.db import migrations


def add_snippet_hash(apps, schema_editor):
    """Calculate and add digest hash of the snippet."""

    ModulemdDefaults = apps.get_model("rpm", "ModulemdDefaults")
    modules_to_update = []
    for mmd in ModulemdDefaults.objects.filter(digest__in=('', None)).only("snippet").iterator():
        mmd.digest = hashlib.sha256(mmd.snippet.encode()).hexdigest()
        modules_to_update.append(mmd)
    ModulemdDefaults.objects.bulk_update(modules_to_update, fields=["digest"])

    Modulemd = apps.get_model("rpm", "Modulemd")
    modules_to_update = []
    for mmd in Modulemd.objects.filter(digest__in=('', None)).only("snippet").iterator():
        mmd.digest = hashlib.sha256(mmd.snippet.encode()).hexdigest()
        modules_to_update.append(mmd)
    Modulemd.objects.bulk_update(modules_to_update, fields=["digest"])


class Migration(migrations.Migration):
    dependencies = [
        ("rpm", "0060_rpmpublication_compression_type_empty"),
    ]

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