# Generated by Django 5.1.10 on 2025-08-23 03:42

from django.conf import settings
from django.db import migrations, utils



def migrate_teams_to_roles(apps, schema_editor):

    try:

        teams = apps.get_model(
            'access.Team'
        ).objects.select_related(
            'organization'
        ).prefetch_related(
            'permissions__content_type',
            'user_set'
        )

        print('\n\nFound teams to migrate.\n')

        for team in teams:

            print(f'    Migrating team {team.team_name}')

            role_kwargs: dict = {
                'organization': team.organization,
                'model_notes': team.model_notes,
                'name': team.team_name,
            }


            # django.db.utils.IntegrityError
            role = apps.get_model('access.Role').objects.create(
                **role_kwargs
            )

            print(f"        Created role {role_kwargs['name']}")

            # permission_args = []
            # for permission in team.permissions.all():
            #     permission_args += [ permission.id ]

            role.permissions.set(
                # permission_args
                [ permission.id for permission in team.permissions.all() ]
            )

            print(f"        Permissions from team {team.name} added to role {role_kwargs['name']}")

            role.groups.add( team.id )

            team.name = 'migrated-team-' + team.name
            team.save()


            print(f"        Migrating Team Users from team {team.team_name}")
            for team_user in team.team.all():

                _user_in_group = False
                for user_group in team_user.user.groups.all():

                    if user_group.id == team.id:
                        _user_in_group = True

                if not _user_in_group:
                    team_user.user.groups.add( team.id )

                    print(f"            User {team_user.user.username} from team {team.team_name} added to group {team.name}")

            # role_content_type = apps.get_model("contenttypes", "ContentType").objects.get(
            #     app_label = role._meta.app_label,
            #     model = role._meta.model_name
            # )

            for note in team.notes.all():

                print(f"        Migrating Team Note from team {team.team_name} to role {role_kwargs['name']}")

                notes_kwargs: dict = {
                    'organization': team.organization,
                    'model': role,
                    'content_type': apps.get_model("contenttypes", "ContentType").objects.get(
                        app_label = role._meta.app_label,
                        model = role._meta.model_name
                    ),
                    'body': note.content,
                    'created_by': note.created_by,
                    'created': note.created,
                    'modified': note.modified,
                }

                new_note = apps.get_model('access.RoleCenturionModelNote').objects.create( **notes_kwargs )
                new_note.save()

            team.permissions.clear()
            team.delete( keep_parents = True )
            print(f"        Removed team {team.team_name}")


        print(f'Migration from Teams to Roles completed.')

    except LookupError:
        print(f'Teams model does not exist, nothing to migrate.')





class Migration(migrations.Migration):

    dependencies = [
        ("access", "0013_role_groups_role_users"),
        ("assistance", "0008_alter_knowledgebaseaudithistory_options_and_more"),
        ("core", "0025_alter_manufactureraudithistory_options_and_more"),
        ("project_management", "0008_alter_projectaudithistory_options_and_more"),
    ]

    operations = [
        migrations.RunPython(migrate_teams_to_roles, migrations.RunPython.noop),
    ]
