# Generated by Django 5.2.5 on 2025-09-09 16:48

from django.db import migrations, models


def get_active(apps, schema_editor):
    from django.core.cache import cache
    ConfigRevision = apps.get_model('core', 'ConfigRevision')
    version = None
    revision = None

    # Try and get the latest version from cache
    try:
        version = cache.get('config_version')
    except Exception:
        pass

    # If there is a version in cache, attempt to set revision to the current version from cache
    # If the version in cache does not exist or there is no version, try the lastest revision in the database
    if not version or (version and not (revision := ConfigRevision.objects.filter(pk=version).first())):
        revision = ConfigRevision.objects.order_by('-created').first()

    # If there is a revision set, set the active revision
    if revision:
        revision.active = True
        revision.save()


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0018_concrete_objecttype'),
    ]

    operations = [
        migrations.AddField(
            model_name='configrevision',
            name='active',
            field=models.BooleanField(default=False),
        ),
        migrations.RunPython(code=get_active, reverse_code=migrations.RunPython.noop),
        migrations.AddConstraint(
            model_name='configrevision',
            constraint=models.UniqueConstraint(
                condition=models.Q(('active', True)), fields=('active',), name='unique_active_config_revision'
            ),
        ),
    ]
