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


def assign_default_role(apps, schema_editor):
    Role = apps.get_model("users", "Role")
    User = apps.get_model("users", "User")
    role, _ = Role.objects.get_or_create(name="Unassigned")
    User.objects.filter(role__isnull=True).update(role=role)


class Migration(migrations.Migration):
    dependencies = [
        ("users", "0003_role"),
    ]

    operations = [
        migrations.AddField(
            model_name="user",
            name="role",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.PROTECT,
                to="users.role",
            ),
            preserve_default=False,
        ),
        migrations.RunPython(assign_default_role, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="user",
            name="role",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.PROTECT,
                to="users.role",
            ),
        ),
    ]
