# Generated by Django 3.2.16 on 2022-11-25 11:45

from django.db import migrations

from nautobot.core.utils.migrations import update_object_change_ct_for_replaced_models
from nautobot.extras.utils import migrate_role_data


def migrate_data_from_legacy_role_to_new_role(apps, schema):
    """Transfer data from legacy_role to new_role."""
    to_role_model = apps.get_model("extras", "Role")
    for model_name in ("Device", "Rack"):
        model = apps.get_model("dcim", model_name)
        from_role_model = apps.get_model("dcim", f"{model_name}Role")
        migrate_role_data(
            model_to_migrate=model,
            from_role_field_name="legacy_role",
            from_role_model=from_role_model,
            to_role_field_name="new_role",
            to_role_model=to_role_model,
        )

    update_object_change_ct_for_replaced_models(
        apps=apps,
        new_app_model={"app_name": "extras", "model": "role"},
        replaced_apps_models=[
            {"app_name": "dcim", "model": "rackrole"},
            {"app_name": "dcim", "model": "devicerole"},
        ],
    )


def reverse_role_data_migrate(apps, schema):
    """Transfer data from new_role to legacy_role."""
    from_role_model = apps.get_model("extras", "Role")
    for model_name in ("Device", "Rack"):
        model = apps.get_model("dcim", model_name)
        to_role_model = apps.get_model("dcim", f"{model_name}Role")
        migrate_role_data(
            model_to_migrate=model,
            from_role_field_name="new_role",
            from_role_model=from_role_model,
            to_role_field_name="legacy_role",
            to_role_model=to_role_model,
        )
    update_object_change_ct_for_replaced_models(
        apps=apps,
        new_app_model={"app_name": "extras", "model": "role"},
        replaced_apps_models=[
            {"app_name": "dcim", "model": "rackrole"},
            {"app_name": "dcim", "model": "devicerole"},
        ],
        reverse_migration=True,
    )


class Migration(migrations.Migration):
    dependencies = [
        ("dcim", "0028_alter_device_and_rack_role_add_new_role"),
    ]

    operations = [
        migrations.RunPython(migrate_data_from_legacy_role_to_new_role, reverse_role_data_migrate),
    ]
