"""
Data migration to copy PhotoSubmission data to EditSubmission.

This migration copies all PhotoSubmission rows to EditSubmission with submission_type="PHOTO".
After this migration, PhotoSubmission model can be safely removed.
"""

from django.db import migrations


def migrate_photo_submissions(apps, schema_editor):
    """Copy PhotoSubmission data to EditSubmission."""
    PhotoSubmission = apps.get_model("moderation", "PhotoSubmission")
    EditSubmission = apps.get_model("moderation", "EditSubmission")
    ContentType = apps.get_model("contenttypes", "ContentType")

    # Get EditSubmission content type for reference
    edit_submission_ct = ContentType.objects.get_for_model(EditSubmission)

    migrated = 0
    for photo_sub in PhotoSubmission.objects.all():
        # Create EditSubmission from PhotoSubmission
        EditSubmission.objects.create(
            user=photo_sub.user,
            content_type=photo_sub.content_type,
            object_id=photo_sub.object_id,
            submission_type="PHOTO",
            changes={},  # Photos don't have field changes
            reason="Photo submission",  # Default reason
            status=photo_sub.status,
            created_at=photo_sub.created_at,
            handled_by=photo_sub.handled_by,
            handled_at=photo_sub.handled_at,
            notes=photo_sub.notes,
            claimed_by=photo_sub.claimed_by,
            claimed_at=photo_sub.claimed_at,
            # Photo-specific fields
            photo=photo_sub.photo,
            caption=photo_sub.caption,
            date_taken=photo_sub.date_taken,
        )
        migrated += 1

    if migrated:
        print(f"Migrated {migrated} PhotoSubmission(s) to EditSubmission")


def reverse_migration(apps, schema_editor):
    """Remove migrated EditSubmissions with type PHOTO."""
    EditSubmission = apps.get_model("moderation", "EditSubmission")
    deleted, _ = EditSubmission.objects.filter(submission_type="PHOTO").delete()
    if deleted:
        print(f"Deleted {deleted} PHOTO EditSubmission(s)")


class Migration(migrations.Migration):

    dependencies = [
        ("moderation", "0011_add_photo_fields_to_editsubmission"),
    ]

    operations = [
        migrations.RunPython(migrate_photo_submissions, reverse_migration),
    ]
