# Generated by Django 3.2.13 on 2022-07-05 11:32

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


# pylint: disable=unused-argument
def link_created_by(apps, schema_editor):
    """
    Convert the ``created_by`` char field to a foreign key

    :param apps: The configuration of installed applications
    :type apps: ~django.apps.registry.Apps

    :param schema_editor: The database abstraction layer that creates actual SQL code
    :type schema_editor: ~django.db.backends.base.schema.BaseDatabaseSchemaEditor
    """
    Document = apps.get_model("cms", "Document")
    Group = apps.get_model("auth", "Group")
    for document in Document.objects.filter(created_by__isnull=False):
        group, created = Group.objects.get_or_create(name=document.created_by)
        document.created_by_link = group
        document.save()


# pylint: disable=unused-argument
def reverse_created_by(apps, schema_editor):
    """
    Convert the ``created_by`` field from foreign key to a char field

    :param apps: The configuration of installed applications
    :type apps: ~django.apps.registry.Apps

    :param schema_editor: The database abstraction layer that creates actual SQL code
    :type schema_editor: ~django.db.backends.base.schema.BaseDatabaseSchemaEditor
    """
    Document = apps.get_model("cms", "Document")
    Group = apps.get_model("auth", "Group")
    for document in Document.objects.filter(created_by_link__isnull=False):
        group, created = Group.objects.get_or_create(id=document.created_by_link.id)
        document.created_by = group.name
        document.save()


class Migration(migrations.Migration):

    dependencies = [
        ("cms", "0006_convert_group_api_key"),
    ]

    operations = [
        migrations.AddField(
            model_name="document",
            name="created_by_link",
            field=models.ForeignKey(
                blank=True,
                max_length=255,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="auth.group",
                verbose_name="created by",
            ),
        ),
        migrations.RunPython(link_created_by, reverse_created_by),
        migrations.RemoveField(
            model_name="document",
            name="created_by",
        ),
        migrations.RenameField(
            model_name="document",
            old_name="created_by_link",
            new_name="created_by",
        ),
    ]
