# Generated by Django 5.2.5 on 2025-10-11 12:18

import django.db.models.deletion
from django.db import migrations, models


def migrate_channels_to_notificationchannel(apps, schema_editor):
    """Migrate data from channels JSONField to NotificationChannel model."""
    Notification = apps.get_model("generic_notifications", "Notification")
    NotificationChannel = apps.get_model("generic_notifications", "NotificationChannel")

    for notification in Notification.objects.all():
        # Access the channels_old JSONField (renamed to avoid conflict)
        channels_data = notification.channels_old if hasattr(notification, "channels_old") else []

        # Create NotificationChannel entries for each channel
        for channel in channels_data:
            delivery, created = NotificationChannel.objects.get_or_create(
                notification=notification,
                channel=channel,
            )

            # If this is the email channel and email_sent_at is set, update sent_at
            if notification.email_sent_at:
                delivery.sent_at = notification.email_sent_at
                delivery.save()


def reverse_migrate_channels(apps, schema_editor):
    """Reverse migration: copy data back from NotificationChannel to channels JSONField."""
    Notification = apps.get_model("generic_notifications", "Notification")
    NotificationChannel = apps.get_model("generic_notifications", "NotificationChannel")

    for notification in Notification.objects.all():
        # Rebuild channels list from NotificationChannel entries
        channels = list(NotificationChannel.objects.filter(notification=notification).values_list("channel", flat=True))
        notification.channels_old = channels

        # Restore email_sent_at from email NotificationChannel
        try:
            email_delivery = NotificationChannel.objects.get(notification=notification, channel="email")
            if email_delivery.sent_at:
                notification.email_sent_at = email_delivery.sent_at
        except NotificationChannel.DoesNotExist:
            pass

        notification.save()


class Migration(migrations.Migration):
    dependencies = [
        ("generic_notifications", "0001_initial"),
    ]

    operations = [
        # First, rename the channels field to avoid naming conflict with the related_name
        migrations.RenameField(
            model_name="notification",
            old_name="channels",
            new_name="channels_old",
        ),
        # Create the new NotificationChannel model
        migrations.CreateModel(
            name="NotificationChannel",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("channel", models.CharField(max_length=20)),
                ("sent_at", models.DateTimeField(blank=True, null=True)),
                (
                    "notification",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="channels",
                        to="generic_notifications.notification",
                    ),
                ),
            ],
            options={
                "indexes": [
                    models.Index(fields=["notification", "channel", "sent_at"], name="generic_not_notific_956af2_idx"),
                    models.Index(fields=["channel", "sent_at"], name="generic_not_channel_cfce4f_idx"),
                ],
                "unique_together": {("notification", "channel")},
            },
        ),
        # Migrate the data
        migrations.RunPython(
            migrate_channels_to_notificationchannel,
            reverse_migrate_channels,
        ),
        # Rename back to channels for migration 3 to handle removal
        migrations.RenameField(
            model_name="notification",
            old_name="channels_old",
            new_name="channels",
        ),
    ]
