from django.core.cache import cache
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from core.utils.Permission import ReadOnly
from settings.models import Setting
from settings.serializers import SettingSerializer
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page


# Create your views here.
class SettingDetailView(APIView):
    permission_classes = [ReadOnly]

    @method_decorator(cache_page(60 * 5))
    def get(self, request):
        try:
            # Cache'den veri kontrolü
            cache_key = 'active_setting'
            cached_data = cache.get(cache_key)

            if cached_data:
                return Response(cached_data)

            # Cache'de yoksa veritabanından al
            setting = Setting.objects.filter(is_active=True).first()
            if setting:
                serializer = SettingSerializer(setting, context={'request': request})
                # 5 dakika (300 saniye) cache'le
                cache.set(cache_key, serializer.data, timeout=300)
                return Response(serializer.data)
            else:
                return Response({"error": "No settings found"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
