from rest_framework import permissions, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.request import Request
from rest_framework.response import Response

from apps.reader.models import ReadingSettings
from apps.reader.serializers import ReadingSettingsSerializer


@api_view(["GET", "PUT", "PATCH"])
@permission_classes([permissions.IsAuthenticated])
def reading_settings_view(request: Request) -> Response:
    """Get or update the current user's reading settings.

    GET  → return existing settings (auto-create defaults if missing)
    PUT  → create or fully replace settings
    PATCH → partial update
    """
    user = request.user
    settings, created = ReadingSettings.objects.get_or_create(user=user)

    if request.method == "GET":
        serializer = ReadingSettingsSerializer(settings)
        return Response(serializer.data)

    if request.method == "PUT":
        serializer = ReadingSettingsSerializer(settings, data=request.data)
    elif request.method == "PATCH":
        serializer = ReadingSettingsSerializer(settings, data=request.data, partial=True)

    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data, status=status.HTTP_200_OK)