"""Data migration: seed NotificationTemplate rows for REP verbs (WS2.2).

Idempotent — uses the same get_or_create pattern as the seed_notification_templates
management command. Running this migration on a database that already has rows
for the new REP verbs is a no-op.

Reverse: do nothing. We do not want to drop seeded templates on rollback —
operators may have edited them.
"""

from __future__ import annotations

from django.db import migrations


def _seed_rep_templates(apps, schema_editor):
    NotificationTemplate = apps.get_model("core", "NotificationTemplate")
    # Import the canonical template list lazily so test discovery and migration
    # rollback do not blow up if the module is renamed in a future refactor.
    from apps.core.notifications.default_templates import DEFAULT_TEMPLATES

    rep_entries = [e for e in DEFAULT_TEMPLATES if str(e["verb"]).startswith("rep_")]
    for entry in rep_entries:
        NotificationTemplate.objects.get_or_create(
            verb=entry["verb"],
            defaults={
                "name": entry["name"],
                "subject": entry["subject"],
                "body_text": entry.get("body_text", ""),
                "body_html": entry.get("body_html", ""),
                "headline_default": entry.get("headline_default", ""),
                "action_label_default": entry.get("action_label_default", "Open in IILMP"),
                "is_active": True,
            },
        )


def _noop_reverse(apps, schema_editor):
    # Operators may have edited these rows; do not roll them back.
    return


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0023_expand_notification_verb_rep"),
    ]

    operations = [
        migrations.RunPython(_seed_rep_templates, _noop_reverse),
    ]
