# Generated by Django 4.2.24 on 2025-12-13 16:56
"""
Data migration to grant 'permission_corpus' to all existing corpus creators.

This enables corpus owners to control visibility (is_public) of their corpuses
via the SetCorpusVisibility mutation, which previously required superuser access.

Part of Phase 1 sharing implementation - see docs/architecture/sharing.md
"""

from django.db import migrations


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

    Uses guardian's assign_perm directly rather than set_permissions_for_obj_to_user
    to avoid affecting other permissions the user may have.
    """
    from guardian.shortcuts import assign_perm

    Corpus = apps.get_model("corpuses", "Corpus")

    # Process corpuses with creators
    corpuses = Corpus.objects.select_related("creator").exclude(creator__isnull=True)

    granted_count = 0
    for corpus in corpuses.iterator(chunk_size=500):
        try:
            assign_perm("corpuses.permission_corpus", corpus.creator, corpus)
            granted_count += 1
        except Exception:
            # Skip if permission already exists or other issue
            pass

    print(f"\nGranted permission_corpus to {granted_count} corpus creators")


def revoke_permission_from_creators(apps, schema_editor):
    """Reverse migration - remove permission_corpus from creators."""
    from guardian.shortcuts import remove_perm

    Corpus = apps.get_model("corpuses", "Corpus")

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

    for corpus in corpuses.iterator(chunk_size=500):
        try:
            remove_perm("corpuses.permission_corpus", corpus.creator, corpus)
        except Exception:
            pass


class Migration(migrations.Migration):

    dependencies = [
        ("corpuses", "0026_remove_corpusdocumentfolder"),
    ]

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