# Generated by Django 4.2.24 on 2025-12-13 19:00
"""
Fix migration to grant 'permission_corpus' to all existing corpus creators.

The previous migration (0027) failed silently because:
1. It used apps.get_model() which returns historical models
2. Guardian's assign_perm needs actual models for ContentType lookup
3. Exceptions were silently swallowed

This migration uses guardian's lower-level API with explicit ContentType lookup.
"""

from django.db import migrations


def grant_permission_to_creators(apps, schema_editor):
    """
    Grant 'permission_corpus' to all existing corpus creators.

    Uses guardian's UserObjectPermission directly with ContentType lookup
    to work correctly in migrations.
    """
    from django.contrib.auth import get_user_model
    from django.contrib.auth.models import Permission
    from django.contrib.contenttypes.models import ContentType

    from guardian.models import UserObjectPermission

    # Get the actual Corpus model (not historical)
    from opencontractserver.corpuses.models import Corpus

    User = get_user_model()

    # Get ContentType for Corpus
    content_type = ContentType.objects.get_for_model(Corpus)

    # Get the permission object
    try:
        permission = Permission.objects.get(
            codename="permission_corpus", content_type=content_type
        )
    except Permission.DoesNotExist:
        print("\nERROR: permission_corpus Permission does not exist!")
        print("Run 'python manage.py migrate' to create permissions first.")
        return

    # Process all corpuses with creators
    corpuses = Corpus.objects.select_related("creator").exclude(creator__isnull=True)
    total_count = corpuses.count()
    print(f"\nFound {total_count} corpuses with creators")

    granted_count = 0
    already_had_count = 0
    error_count = 0

    for corpus in corpuses.iterator(chunk_size=500):
        try:
            # Check if permission already exists
            exists = UserObjectPermission.objects.filter(
                user=corpus.creator,
                permission=permission,
                content_type=content_type,
                object_pk=str(corpus.pk),
            ).exists()

            if exists:
                already_had_count += 1
            else:
                # Create the permission
                UserObjectPermission.objects.create(
                    user=corpus.creator,
                    permission=permission,
                    content_type=content_type,
                    object_pk=str(corpus.pk),
                )
                granted_count += 1
        except Exception as e:
            error_count += 1
            print(f"  Error for corpus {corpus.id}: {e}")

    print(f"\nResults:")
    print(f"  Granted new permissions: {granted_count}")
    print(f"  Already had permission: {already_had_count}")
    print(f"  Errors: {error_count}")


def revoke_permission_from_creators(apps, schema_editor):
    """Reverse migration - remove permission_corpus from creators."""
    from django.contrib.auth.models import Permission
    from django.contrib.contenttypes.models import ContentType

    from guardian.models import UserObjectPermission

    from opencontractserver.corpuses.models import Corpus

    content_type = ContentType.objects.get_for_model(Corpus)

    try:
        permission = Permission.objects.get(
            codename="permission_corpus", content_type=content_type
        )
    except Permission.DoesNotExist:
        return

    corpuses = Corpus.objects.select_related("creator").exclude(creator__isnull=True)

    for corpus in corpuses.iterator(chunk_size=500):
        UserObjectPermission.objects.filter(
            user=corpus.creator,
            permission=permission,
            content_type=content_type,
            object_pk=str(corpus.pk),
        ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("corpuses", "0027_grant_permission_to_corpus_creators"),
    ]

    operations = [
        migrations.RunPython(
            grant_permission_to_creators,
            revoke_permission_from_creators,
        ),
    ]
