# Generated by Django 4.2.22 on 2026-01-05 08:36

from django.db import migrations

def move_issue_user_properties_to_project_user_properties(apps, schema_editor):
    ProjectMember = apps.get_model('db', 'ProjectMember')
    ProjectUserProperty = apps.get_model('db', 'ProjectUserProperty')

    # Get all project members
    project_members = ProjectMember.objects.filter(deleted_at__isnull=True).values('member_id', 'project_id', 'preferences', 'sort_order')

    # create a mapping with consistent ordering 
    pm_dict = {
        (pm['member_id'], pm['project_id']): pm
        for pm in project_members
    }
    
    # Get all project user properties
    properties_to_update = []
    for projectuserproperty in ProjectUserProperty.objects.filter(deleted_at__isnull=True):
        pm = pm_dict.get((projectuserproperty.user_id, projectuserproperty.project_id))
        if pm:
            projectuserproperty.preferences = pm['preferences']
            projectuserproperty.sort_order = pm['sort_order']
            properties_to_update.append(projectuserproperty)

    ProjectUserProperty.objects.bulk_update(properties_to_update, ['preferences', 'sort_order'], batch_size=2000)



def migrate_existing_api_tokens(apps, schema_editor):
    APIToken = apps.get_model('db', 'APIToken')
    
    # Update all the existing non-service api tokens to not have a workspace
    APIToken.objects.filter(is_service=False, user__is_bot=False).update(
        workspace_id=None,

    )
    return


class Migration(migrations.Migration):

    dependencies = [
        ('db', '0114_projectuserproperty_delete_issueuserproperty_and_more'),
    ]

    operations = [
        migrations.RunPython(move_issue_user_properties_to_project_user_properties, reverse_code=migrations.RunPython.noop),
        migrations.RunPython(migrate_existing_api_tokens, reverse_code=migrations.RunPython.noop),
    ]
