from django.db import migrations

def create_groups(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    
    # Define roles
    roles = {
        'Главный механик': ['view_fleetunit', 'add_maintenance', 'change_maintenance', 'view_maintenance', 'add_breakdown', 'change_breakdown', 'view_breakdown', 'add_partrequest', 'change_partrequest', 'view_partrequest'],
        'Механик': ['view_fleetunit', 'change_maintenance', 'view_maintenance', 'add_breakdown', 'view_breakdown', 'add_partrequest', 'view_partrequest'],
        'Снабжение': ['view_fleetunit', 'view_partrequest', 'change_partrequest', 'add_partrequest'],
    }
    
    for role_name, perms in roles.items():
        group, created = Group.objects.get_or_create(name=role_name)
        for perm_code in perms:
            try:
                perm = Permission.objects.get(codename=perm_code)
                group.permissions.add(perm)
            except Permission.DoesNotExist:
                pass

class Migration(migrations.Migration):
    dependencies = [
        ('core', '0002_breakdown_notes_breakdown_photo_fleetunit_qr_code_and_more'),
        ('auth', '0012_alter_user_first_name_max_length'),
    ]

    operations = [
        migrations.RunPython(create_groups),
    ]