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.Permission import ReadOnly
from settings.models import Setting, SiteSettings
from settings.serializers import SettingSerializer, SettingOpenCloseSerializer

CACHE_TTL_SECONDS = 60 * 5


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

    def get(self, request):
        try:
            cache_key = 'settings:detail'
            cached_data = cache.get(cache_key)
            if cached_data:
                return Response(cached_data)

            # İlk kaydı getir (veya istediğin koşula göre)
            setting = Setting.objects.filter(is_active=True).first()
            if setting:
                serializer = SettingSerializer(setting)
                cache.set(cache_key, serializer.data, timeout=CACHE_TTL_SECONDS)
                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)


class SettingOpenCloseDetailView(APIView):
    permission_classes = [ReadOnly]

    def get(self, request):
        try:
            cache_key = 'settings:site_status'
            cached_data = cache.get(cache_key)
            if cached_data:
                return Response(cached_data)

            # İlk kaydı getir (veya istediğin koşula göre)
            setting = SiteSettings.objects.filter(is_active=True).first()
            if setting:
                serializer = SettingOpenCloseSerializer(setting)
                cache.set(cache_key, serializer.data, timeout=CACHE_TTL_SECONDS)
                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)
