# Generated by Django 6.0 on 2026-02-09 22:04

import django.db.models.deletion
from django.db import migrations, models


def forwards(apps, schema_editor):
    from resources.models import Role, ObjectPermission

    if schema_editor.connection.alias != "default":
        return
    for role in Role.objects.all():
        for perm in role.permissions.order_by("label"):
            object_class, crud_right = perm.label.split(".")
            object_permission, _ = ObjectPermission.objects.get_or_create(
                object_class=object_class, role=role
            )
            if crud_right == "create":
                object_permission.object_create = True
            if crud_right == "read":
                object_permission.object_read = True
            if crud_right == "update":
                object_permission.object_update = True
            if crud_right == "delete":
                object_permission.object_delete = True
            object_permission.save()


class Migration(migrations.Migration):
    dependencies = [
        ("resources", "0047_filetype_serve_with_hls"),
    ]

    operations = [
        migrations.CreateModel(
            name="ObjectPermission",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("object_class", models.TextField(db_index=True)),
                ("object_pk", models.IntegerField(null=True)),
                ("object_create", models.BooleanField(default=False)),
                ("object_read", models.BooleanField(default=False)),
                ("object_update", models.BooleanField(default=False)),
                ("object_delete", models.BooleanField(default=False)),
                (
                    "role",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE, to="resources.role"
                    ),
                ),
            ],
        ),
        migrations.RunPython(forwards),
    ]
