# Generated by Django 4.2.5 on 2024-02-13 15:40

from django.db import migrations, models


def add_current_share_reasons_to_audit_log(apps, schema_editor):
    log_entry_model = apps.get_model('audit', 'LogEntry')
    shared_secret_data_model = apps.get_model('secrets', 'SharedSecretData')
    shares = shared_secret_data_model.objects.all().exclude(granted_by__isnull=True)
    shared_log_entries = log_entry_model.objects.filter(
        category__in=['secret_shared', 'secret_superuser_shared']
    ).only('secret__id', 'actor__id', 'reason')

    for share in shares:
        matched_entry = shared_log_entries.filter(
            actor__id=share.granted_by.id,
            secret__id=share.secret.id,
        ).order_by('time').last()

        # Matching can fail for immediate shares while creating new secrets
        if matched_entry:
            matched_entry.reason = share.grant_description
            matched_entry.save(update_fields=['reason'])


class Migration(migrations.Migration):
    dependencies = [
        ("audit", "0005_alter_logentry_category"),
        ("secrets", "0032_alter_sharedsecretdata_granted_by")
    ]

    operations = [
        migrations.AddField(
            model_name="logentry",
            name="reason",
            field=models.TextField(blank=True, null=True),
        ),
        migrations.RunPython(
            code=add_current_share_reasons_to_audit_log,
            reverse_code=migrations.RunPython.noop,
        ),
    ]
