"""
通知模块视图 - App端
"""
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from drf_spectacular.utils import extend_schema

from utils.response import success, error
from utils.exceptions import ErrorCode
from apps.admins.authentication import AppJWTAuthentication
from .models import Notification
from .serializers import NotificationSerializer


@extend_schema(tags=['通知'])
class NotificationViewSet(viewsets.ViewSet):
    """通知视图集（App端）"""

    authentication_classes = [AppJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def list(self, request):
        """
        通知列表
        GET /api/v1/notifications/
        """
        queryset = Notification.objects.filter(user=request.user)

        # 按类型筛选
        ntype = request.query_params.get('type')
        if ntype:
            queryset = queryset.filter(type=ntype)

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 20))
        start = (page - 1) * page_size
        end = start + page_size

        total = queryset.count()
        unread_count = Notification.objects.filter(user=request.user, is_read=False).count()
        notifications = queryset[start:end]

        return success(data={
            'total': total,
            'unread_count': unread_count,
            'items': NotificationSerializer(notifications, many=True).data,
        })

    def destroy(self, request, pk=None):
        """
        删除通知
        DELETE /api/v1/notifications/{id}/
        """
        try:
            notification = Notification.objects.get(id=pk, user=request.user)
        except Notification.DoesNotExist:
            return error(code=ErrorCode.NOTIFICATION_NOT_FOUND, message='通知不存在')
        notification.delete()
        return success(message='删除成功')

    @action(detail=True, methods=['post'])
    def read(self, request, pk=None):
        """
        标记已读
        POST /api/v1/notifications/{id}/read/
        """
        try:
            notification = Notification.objects.get(id=pk, user=request.user)
        except Notification.DoesNotExist:
            return error(code=ErrorCode.NOTIFICATION_NOT_FOUND, message='通知不存在')

        notification.is_read = True
        notification.save(update_fields=['is_read'])
        return success(message='已标记为已读')

    @action(detail=False, methods=['post'], url_path='read-all')
    def read_all(self, request):
        """
        全部已读
        POST /api/v1/notifications/read-all/
        """
        count = Notification.objects.filter(
            user=request.user, is_read=False
        ).update(is_read=True)
        return success(data={'count': count}, message=f'已将{count}条通知标记为已读')
