from rest_framework import serializers

from apps.chat.models import (
    ChatAuditEvent,
    ChatConversation,
    ChatGlobalConfiguration,
    ChatMessage,
    ChatNotification,
    ChatRetentionPolicy,
    ChatUserPreference,
    ConversationMember,
    MessageAttachment,
    SharedPageReference,
)


def serialize_message(msg: ChatMessage, *, requester_id=None) -> dict:
    if msg.is_deleted_for_everyone:
        body = "[Message removed under policy]"
    else:
        body = msg.body

    refs = [
        {
            "id": str(r.id),
            "route_key": r.route_key,
            "page_title": r.page_title,
            "module_name": r.module_name,
            "object_type": r.object_type,
            "object_id": r.object_id,
            "object_ref_code": r.object_ref_code,
            "created_at": r.created_at.isoformat(),
        }
        for r in msg.page_references.all()
    ]
    atts = [
        {
            "id": str(a.id),
            "original_filename": a.original_filename,
            "mime_type": a.mime_type,
            "file_extension": a.file_extension,
            "size_bytes": a.size_bytes,
            "scan_status": a.scan_status,
            "download_url": f"/api/chat/attachments/{a.id}/",
        }
        for a in msg.attachments.all()
    ]
    reactions: dict[str, list[str]] = {}
    for rx in msg.reactions.select_related("user").all():
        reactions.setdefault(rx.emoji, []).append(rx.user.username)

    return {
        "id": str(msg.id),
        "conversation_id": str(msg.conversation_id),
        "sender": {
            "id": str(msg.sender_id),
            "username": msg.sender.username,
            "full_name": msg.sender.full_name or msg.sender.username,
            "avatar_url": f"/api/profile/avatar/{msg.sender_id}/?thumb=1" if hasattr(msg.sender, "avatar") and msg.sender.avatar else None,
        },
        "client_operation_id": msg.client_operation_id,
        "parent_message_id": str(msg.parent_message_id) if msg.parent_message_id else None,
        "parent_preview": (
            {"id": str(msg.parent_message.id), "sender": msg.parent_message.sender.full_name or msg.parent_message.sender.username, "body": msg.parent_message.body[:90]}
            if msg.parent_message
            else None
        ),
        "message_type": msg.message_type,
        "body": body,
        "status": msg.status,
        "is_edited": msg.is_edited,
        "edited_at": msg.edited_at.isoformat() if msg.edited_at else None,
        "is_deleted_for_everyone": msg.is_deleted_for_everyone,
        "is_pinned": hasattr(msg, "pin") and msg.pin is not None,
        "is_bookmarked": bool(requester_id and msg.bookmarks.filter(user_id=requester_id).exists()),
        "attachments": atts,
        "page_references": refs,
        "reactions": [{"emoji": e, "users": us, "count": len(us)} for e, us in reactions.items()],
        "read_by_count": msg.read_receipts.count(),
        "delivered_count": msg.delivery_receipts.count(),
        "created_at": msg.created_at.isoformat(),
    }


def serialize_conversation(mem: ConversationMember, *, requester_id=None) -> dict:
    conv = mem.conversation
    title = conv.title
    peer = None
    if conv.conversation_type == ChatConversation.Type.DIRECT:
        other = (
            conv.members.select_related("user__avatar", "user__chat_presence", "user__staff_employee__employee_profile__department")
            .filter(left_at__isnull=True)
            .exclude(user_id=requester_id or mem.user_id)
            .first()
        )
        if other:
            title = other.user.full_name or other.user.username
            pres = getattr(other.user, "chat_presence", None)
            emp = getattr(other.user, "staff_employee", None)
            peer = {
                "id": str(other.user_id),
                "username": other.user.username,
                "full_name": title,
                "avatar_url": f"/api/profile/avatar/{other.user_id}/?thumb=1" if hasattr(other.user, "avatar") and other.user.avatar else None,
                "presence": pres.status if pres else "OFFLINE",
                "designation": emp.employee_profile.designation if emp else None,
                "department": emp.employee_profile.department.name if emp and emp.employee_profile.department else None,
            }

    last_msg = conv.messages.filter(is_deleted_for_everyone=False).exclude(status=ChatMessage.Status.DRAFT).order_by("-created_at").first()
    return {
        "id": str(conv.id),
        "conversation_type": conv.conversation_type,
        "title": title,
        "description": conv.description,
        "visibility": conv.visibility,
        "posting_policy": conv.posting_policy,
        "is_mandatory": conv.is_mandatory,
        "allow_attachments": conv.allow_attachments,
        "department_id": str(conv.department_id) if conv.department_id else None,
        "project_id": str(conv.project_id) if conv.project_id else None,
        "site_id": str(conv.site_id) if conv.site_id else None,
        "peer": peer,
        "member_role": mem.role,
        "member_count": conv.members.filter(left_at__isnull=True).count(),
        "unread_count": mem.unread_count,
        "marked_unread": mem.marked_unread,
        "is_pinned": mem.is_pinned,
        "is_muted": mem.is_muted,
        "is_archived": mem.is_archived,
        "draft_text": mem.draft_text,
        "draft_page_refs": mem.draft_page_refs,
        "last_message": (
            {
                "id": str(last_msg.id),
                "sender_name": last_msg.sender.full_name or last_msg.sender.username,
                "body": last_msg.body[:90] or ("Shared Page Link" if last_msg.message_type == "PAGE_LINK" else "Attachment"),
                "created_at": last_msg.created_at.isoformat(),
            }
            if last_msg
            else None
        ),
        "last_message_at": conv.last_message_at.isoformat() if conv.last_message_at else conv.created_at.isoformat(),
    }


class ChatUserPreferenceSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatUserPreference
        exclude = ["user"]


class ChatGlobalConfigSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatGlobalConfiguration
        exclude = ["company"]


class ChatRetentionPolicySerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatRetentionPolicy
        exclude = ["company"]


class ChatNotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatNotification
        fields = ["id", "conversation", "message", "notification_type", "title", "preview_text", "is_read", "read_at", "created_at"]


class ChatAuditEventSerializer(serializers.ModelSerializer):
    actor_username = serializers.CharField(source="actor.username", read_only=True)

    class Meta:
        model = ChatAuditEvent
        fields = ["id", "company", "actor", "actor_username", "conversation", "action", "metadata", "created_at"]

