# Generated by Django 4.2.29 on 2026-04-02 14:32

from django.db import migrations


def port_role_to_roles(apps, schema_editor):
    User = apps.get_model('users', 'User')
    Role = apps.get_model('users', 'Role')

    # Ensure roles exist
    default_roles = ['CEO', 'PM', 'TL', 'BD', 'Member', 'Finance', 'HR']
    for r in default_roles:
        Role.objects.get_or_create(name=r)

    # Migrate users
    for user in User.objects.all():
        if user.role:
            role_obj, _ = Role.objects.get_or_create(name=user.role)
            user.roles.add(role_obj)

def rollback_roles(apps, schema_editor):
    """
    Reverse migration: take the first role from roles 
    and assign it to role
    """
    User = apps.get_model('users', 'User')
    for user in User.objects.all():
        first_role = user.roles.first()
        if first_role:
            user.role = first_role.name
            user.save()

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0002_role_user_roles'),
    ]

    operations = [
        migrations.RunPython(port_role_to_roles, reverse_code=rollback_roles),
    ]
