# Generated by Django 5.2.7 on 2025-10-16 03:21

from django.db import migrations, models
from django.db.models.functions import RowNumber


def remove_duplicates(apps, schema_editor):
    from django.db.models import Window, F
    workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')

    duplicates = workspace_user_resource_permission_model.objects.annotate(
        row_num=Window(
            expression=RowNumber(),
            partition_by=[F('workspace_id'), F('user'), F('auth_target_type'), F('target')],
            order_by=[F('create_time').desc()],
        )
    ).filter(row_num__gt=1)

    ids_to_delete = list(duplicates.values_list('id', flat=True))
    if ids_to_delete:
        workspace_user_resource_permission_model.objects.filter(id__in=ids_to_delete).delete()


class Migration(migrations.Migration):
    dependencies = [
        ('system_manage', '0003_alter_workspaceuserresourcepermission_target'),
        ('users', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(remove_duplicates),
        migrations.AlterUniqueTogether(
            name='workspaceuserresourcepermission',
            unique_together={('workspace_id', 'user', 'auth_target_type', 'target')},
        ),
        migrations.AlterField(
            model_name='systemsetting',
            name='type',
            field=models.IntegerField(choices=[(0, '邮箱'), (1, '私钥秘钥'), (2, '日志清理时间')], default=0,
                                      primary_key=True, serialize=False, verbose_name='设置类型'),
        ),
    ]
