# Generated by Django 4.2.4 on 2023-09-04 14:06

from django.db import migrations, models
import hashlib


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

    Modulemd = apps.get_model("rpm", "Modulemd")
    modules_to_update = []

    for mmd in Modulemd.objects.all().only("snippet").iterator():
        # for the modules that have empty string snippet will be calculated digest of
        # e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
        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", "0051_alter_distributiontree_unique_together_and_more"),
    ]

    operations = [
        migrations.AddField(
            model_name="modulemd",
            name="digest",
            field=models.TextField(null=True),
        ),
        migrations.RunPython(
            code=add_snippet_hash,
            reverse_code=migrations.RunPython.noop,
            elidable=True,
        ),
        migrations.AlterField(
            model_name="modulemd",
            name="digest",
            field=models.TextField(),
        ),
        migrations.AlterUniqueTogether(
            name="modulemd",
            unique_together=set(),
        ),
        migrations.AlterUniqueTogether(
            name="modulemd",
            unique_together={
                ("_pulp_domain", "name", "stream", "version", "context", "arch", "digest")
            },
        ),
    ]
