from django.contrib import admin

from notifier.models import Notifier, NotifierRoute


class NotifierRouteInline(admin.TabularInline):
    model = NotifierRoute
    extra = 0
    fields = ["event_key", "mission_category", "is_enabled", "description"]


@admin.register(Notifier)
class NotifierAdmin(admin.ModelAdmin):
    inlines = [NotifierRouteInline]
    list_display = [
        "id",
        "merchant",
        "name",
        "channel",
        "template_key",
        "is_enabled",
        "created_at",
    ]
    list_filter = ["merchant", "channel", "is_enabled", "created_at"]
    search_fields = ["name", "template_key", "description"]
    readonly_fields = ["created_at", "updated_at"]

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for obj in formset.deleted_objects:
            obj.delete()
        for instance in instances:
            if isinstance(instance, NotifierRoute):
                instance.merchant = form.instance.merchant
            instance.save()
        formset.save_m2m()


@admin.register(NotifierRoute)
class NotifierRouteAdmin(admin.ModelAdmin):
    list_display = [
        "id",
        "merchant",
        "notifier",
        "event_key",
        "mission_category",
        "is_enabled",
        "created_at",
    ]
    list_filter = ["merchant", "event_key", "mission_category", "is_enabled", "created_at"]
    search_fields = ["notifier__name", "description"]
    readonly_fields = ["created_at", "updated_at"]
