"""Introduce shared notification templates and per-record overrides."""

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


def copy_legacy_notification_fields(apps, schema_editor):
    Notification = apps.get_model("django_notify_hub", "Notification")

    for notification in Notification.objects.all().iterator():
        title = notification.title
        lang = "en"
        if isinstance(title, dict) and title:
            lang = str(next(iter(title.keys())))[:10]

        notification.lang = lang
        notification.override_title = notification.title
        notification.override_body = notification.body
        notification.custom_data = notification.data or {}
        notification.custom_priority = notification.priority or "normal"
        notification.custom_channel = notification.channel or "fcm"
        notification.save(
            update_fields=[
                "lang",
                "override_title",
                "override_body",
                "custom_data",
                "custom_priority",
                "custom_channel",
            ]
        )


def restore_legacy_notification_fields(apps, schema_editor):
    Notification = apps.get_model("django_notify_hub", "Notification")

    for notification in Notification.objects.select_related("template").all().iterator():
        if notification.override_title is not None:
            title = notification.override_title
        elif notification.template_id:
            title = notification.template.title
        else:
            title = {}

        if notification.override_body is not None:
            body = notification.override_body
        elif notification.template_id:
            body = notification.template.body
        else:
            body = {}

        if notification.template_id:
            data = notification.template.data
            priority = notification.template.priority
            channel = notification.template.channel
        else:
            data = notification.custom_data or {}
            priority = notification.custom_priority or "normal"
            channel = notification.custom_channel or "fcm"

        notification.title = title
        notification.body = body
        notification.data = data
        notification.priority = priority
        notification.channel = channel
        notification.save(update_fields=["title", "body", "data", "priority", "channel"])


class Migration(migrations.Migration):

    dependencies = [
        ("django_notify_hub", "0001_initial"),
    ]

    operations = [
        migrations.CreateModel(
            name="NotificationTemplate",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("title", models.JSONField(help_text='Shared localised title dict, e.g. {"en": "Hello", "ar": "مرحبا"}', verbose_name="title")),
                ("body", models.JSONField(help_text='Shared localised body dict, e.g. {"en": "You have a new message."}', verbose_name="body")),
                ("data", models.JSONField(blank=True, default=dict, help_text="Shared JSON payload delivered alongside the notification.", verbose_name="metadata")),
                ("priority", models.CharField(choices=[("low", "Low"), ("normal", "Normal"), ("high", "High"), ("critical", "Critical")], default="normal", max_length=20, verbose_name="priority")),
                ("channel", models.CharField(default="fcm", help_text="Shared delivery channel used (fcm, email, websocket, …).", max_length=50, verbose_name="channel")),
                ("created_at", models.DateTimeField(default=django.utils.timezone.now, verbose_name="created at")),
            ],
            options={
                "verbose_name": "Notification template",
                "verbose_name_plural": "Notification templates",
                "ordering": ["-created_at"],
            },
        ),
        migrations.AddField(
            model_name="notification",
            name="custom_channel",
            field=models.CharField(blank=True, default="", help_text="Per-record delivery channel used when no shared template is attached.", max_length=50, verbose_name="channel"),
        ),
        migrations.AddField(
            model_name="notification",
            name="custom_data",
            field=models.JSONField(blank=True, help_text="Per-record metadata used when no shared template is attached.", null=True, verbose_name="custom metadata"),
        ),
        migrations.AddField(
            model_name="notification",
            name="custom_priority",
            field=models.CharField(blank=True, choices=[("low", "Low"), ("normal", "Normal"), ("high", "High"), ("critical", "Critical")], default="", max_length=20, verbose_name="priority"),
        ),
        migrations.AddField(
            model_name="notification",
            name="lang",
            field=models.CharField(default="en", help_text="Language code used when rendering shared template content.", max_length=10, verbose_name="language"),
        ),
        migrations.AddField(
            model_name="notification",
            name="override_body",
            field=models.JSONField(blank=True, help_text="Optional per-record localised body override.", null=True, verbose_name="override body"),
        ),
        migrations.AddField(
            model_name="notification",
            name="override_title",
            field=models.JSONField(blank=True, help_text="Optional per-record localised title override.", null=True, verbose_name="override title"),
        ),
        migrations.AddField(
            model_name="notification",
            name="template",
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="notifications", to="django_notify_hub.notificationtemplate", verbose_name="template"),
        ),
        migrations.RunPython(copy_legacy_notification_fields, restore_legacy_notification_fields),
        migrations.RemoveField(model_name="notification", name="title"),
        migrations.RemoveField(model_name="notification", name="body"),
        migrations.RemoveField(model_name="notification", name="data"),
        migrations.RemoveField(model_name="notification", name="priority"),
        migrations.RemoveField(model_name="notification", name="channel"),
    ]