from __future__ import annotations

from django.contrib import admin
from django.utils.translation import gettext_lazy as _

from vibes_auth.messaging.models import ChatMessage, ChatThread, ThreadStatus


@admin.register(ChatThread)
class ChatThreadAdmin(admin.ModelAdmin):
    list_display = (
        "uuid",
        "user",
        "email",
        "assigned_to",
        "status",
        "last_message_at",
        "is_active",
        "created",
        "modified",
    )
    list_filter = (
        "status",
        "is_active",
        ("assigned_to", admin.EmptyFieldListFilter),
    )
    search_fields = ("uuid", "email", "user__email", "user__username")
    autocomplete_fields = ("user", "assigned_to")
    actions = (
        "close_threads",
        "open_threads",
        "delete_selected",
    )
    readonly_fields = ("created", "modified")

    @admin.action(description=_("Close selected threads"))
    def close_threads(self, request, queryset):  # type: ignore[no-untyped-def]
        queryset.update(status=ThreadStatus.CLOSED)

    @admin.action(description=_("Open selected threads"))
    def open_threads(self, request, queryset):  # type: ignore[no-untyped-def]
        queryset.update(status=ThreadStatus.OPEN)


@admin.register(ChatMessage)
class ChatMessageAdmin(admin.ModelAdmin):
    list_display = ("uuid", "thread", "sender_type", "sender_user", "sent_at")
    list_filter = ("sender_type",)
    search_fields = ("uuid", "thread__uuid", "sender_user__email")
    autocomplete_fields = ("thread", "sender_user")
    readonly_fields = ("created", "modified")
