# Generated by Django 4.1.13 on 2024-07-26 06:08

from django.db import migrations

import common.db.fields


def generate_user_attrs(name, match, value):
    return {
        "type": "attrs",
        "attrs": [
            {
                "name": name,
                "match": match,
                "value": value
            }
        ]
    }


def migrate_assignees_to_users(apps, schema_editor):
    rule_model = apps.get_model('tickets', 'ApprovalRule')
    rules = rule_model.objects.all()
    objs = []

    for rule in rules:
        strategy = rule.strategy
        if strategy == 'super_admin':
            rule.users = generate_user_attrs(
                "system_roles", "m2m", ["00000000-0000-0000-0000-000000000001"]
            )
        elif strategy == 'org_admin':
            rule.users = generate_user_attrs(
                "org_roles", "m2m", ["00000000-0000-0000-0000-000000000005"]
            )
        elif strategy == 'super_org_admin':
            rule.users = {
                "type": "attrs",
                "attrs": [
                    {"name": "org_roles", "match": "m2m", "value": ["00000000-0000-0000-0000-000000000005"]},
                    {"name": "system_roles", "match": "m2m", "value": ["00000000-0000-0000-0000-000000000001"]}
                ]
            }
        elif strategy == 'custom_user':
            user_ids = [str(user_id) for user_id in rule.assignees.values_list('id', flat=True)]
            rule.users = {"type": "ids", "ids": user_ids}
        else:
            continue
        objs.append(rule)

    rule_model.objects.bulk_update(objs, ['users'])


class Migration(migrations.Migration):
    dependencies = [
        ('tickets', '0003_initial_ticket_flow_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='approvalrule',
            name='users',
            field=common.db.fields.JSONManyToManyField(default=dict, to='users.User', verbose_name='Users'),
        ),
        migrations.RunPython(migrate_assignees_to_users),
        migrations.RemoveField(
            model_name='approvalrule',
            name='assignees',
        ),
        migrations.RemoveField(
            model_name='approvalrule',
            name='strategy',
        ),
    ]
