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


def forwards(apps, schema_editor):
    Notifier = apps.get_model("notifier", "Notifier")
    NotifierRoute = apps.get_model("notifier", "NotifierRoute")
    db_alias = schema_editor.connection.alias

    for notifier in Notifier.objects.using(db_alias).all().only("id", "merchant_id", "event_key").iterator():
        NotifierRoute.objects.using(db_alias).get_or_create(
            notifier_id=notifier.id,
            event_key=notifier.event_key,
            mission_category_id=None,
            defaults={
                "merchant_id": notifier.merchant_id,
                "is_enabled": True,
                "description": "由旧版 notifier.event_key 自动迁移生成",
            },
        )


class Migration(migrations.Migration):

    dependencies = [
        ("mission", "0004_missioncategory_refactor"),
        ("notifier", "0001_initial"),
    ]

    operations = [
        migrations.CreateModel(
            name="NotifierRoute",
            fields=[
                ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="创建时间")),
                ("updated_at", models.DateTimeField(auto_now=True, verbose_name="更新时间")),
                ("id", models.BigAutoField(primary_key=True, serialize=False)),
                ("event_key", models.CharField(choices=[("mission.created", "任务已创建"), ("mission.replied", "任务有新回应"), ("mission.completed", "任务已完成"), ("mission.reply_rejected", "任务回应已撤销"), ("mission.reopened", "任务已重新打开"), ("mission.cancelled", "任务已取消")], db_index=True, max_length=100, verbose_name="事件标识")),
                ("is_enabled", models.BooleanField(db_index=True, default=True, verbose_name="是否启用")),
                ("description", models.TextField(blank=True, null=True, verbose_name="备注描述")),
                ("merchant", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="notifier_routes", to="basic_info.merchant", verbose_name="所属商户")),
                ("mission_category", models.ForeignKey(blank=True, help_text="为空时表示该事件的通配路由", null=True, on_delete=django.db.models.deletion.PROTECT, related_name="notifier_routes", to="mission.missioncategory", verbose_name="任务分类路由")),
                ("notifier", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="routes", to="notifier.notifier", verbose_name="通知器")),
            ],
            options={
                "verbose_name": "通知路由",
                "verbose_name_plural": "通知路由",
                "indexes": [models.Index(fields=["merchant", "event_key", "is_enabled"], name="notifier_no_merchan_58d463_idx"), models.Index(fields=["merchant", "mission_category", "is_enabled"], name="notifier_no_merchan_14b7f6_idx")],
                "constraints": [models.UniqueConstraint(fields=("notifier", "event_key", "mission_category"), name="unique_notifier_route_per_scope"), models.UniqueConstraint(condition=Q(mission_category__isnull=True), fields=("notifier", "event_key"), name="unique_notifier_route_global_scope")],
            },
        ),
        migrations.RunPython(forwards, migrations.RunPython.noop),
        migrations.RemoveIndex(
            model_name="notifier",
            name="notifier_no_merchan_c59a7a_idx",
        ),
        migrations.RemoveField(
            model_name="notifier",
            name="event_key",
        ),
        migrations.AddIndex(
            model_name="notifier",
            index=models.Index(fields=["merchant", "channel", "is_enabled"], name="notifier_no_merchan_532b51_idx"),
        ),
    ]
