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

from core.Permission import ReadOnly
from home.models import Home, AboutMe, MyService, MyServiceTitle, MyResume, Education, Experience, Skill, Knowledge, \
    MainMenu
from home.serializers import (HomeSerializer, AboutMeSerializer, MyServiceSerializer, MyServiceTitleSerializer,
                              MyResumeSerializer, EducationSerializer, ExperienceSerializer, SkillSerializer,
                              KnowledgeSerializer, MainMenuSerializer)

CACHE_TTL_SECONDS = 60 * 5


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

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

            home = Home.objects.filter(is_active=True).first()
            if home:
                serializer = HomeSerializer(home)
                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 AboutMeDetailView(APIView):
    permission_classes = [ReadOnly]

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

            aboutme = AboutMe.objects.filter(is_active=True).first()
            if aboutme:
                serializer = AboutMeSerializer(aboutme)
                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 MyServiceList(ListAPIView):
    permission_classes = [ReadOnly]
    queryset = MyService.objects.order_by('-created_at').filter(is_active=True).all()
    serializer_class = MyServiceSerializer

    def list(self, request, *args, **kwargs):
        cache_key = 'home:service_list'
        cached_data = cache.get(cache_key)
        if cached_data:
            return Response(cached_data)

        response = super().list(request, *args, **kwargs)
        cache.set(cache_key, response.data, timeout=CACHE_TTL_SECONDS)
        return response

class MyServiceTitleDetailView(APIView):
    permission_classes = [ReadOnly]

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

            services_title = MyServiceTitle.objects.filter(is_active=True).first()
            if services_title:
                serializer = MyServiceTitleSerializer(services_title)
                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 MyResumeDetailView(APIView):
    permission_classes = [ReadOnly]

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

            resume = MyResume.objects.filter(is_active=True).first()
            if resume:
                serializer = MyResumeSerializer(resume, context={'request': request})
                cache.set(cache_key, serializer.data, timeout=CACHE_TTL_SECONDS)
                return Response(serializer.data)
            else:
                return Response({"error": "No resume found"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class EducationListView(ListAPIView):
    permission_classes = [ReadOnly]
    serializer_class = EducationSerializer

    def get_queryset(self):
        return Education.objects.filter(is_active=True).order_by('-created_at')

    def list(self, request, *args, **kwargs):
        cache_key = 'home:education_list'
        cached_data = cache.get(cache_key)
        if cached_data:
            return Response(cached_data)

        response = super().list(request, *args, **kwargs)
        cache.set(cache_key, response.data, timeout=CACHE_TTL_SECONDS)
        return response


class ExperienceListView(ListAPIView):
    permission_classes = [ReadOnly]
    serializer_class = ExperienceSerializer

    def get_queryset(self):
        return Experience.objects.filter(is_active=True).order_by('-created_at')

    def list(self, request, *args, **kwargs):
        cache_key = 'home:experience_list'
        cached_data = cache.get(cache_key)
        if cached_data:
            return Response(cached_data)

        response = super().list(request, *args, **kwargs)
        cache.set(cache_key, response.data, timeout=CACHE_TTL_SECONDS)
        return response


class SkillListView(ListAPIView):
    permission_classes = [ReadOnly]
    serializer_class = SkillSerializer

    def get_queryset(self):
        return Skill.objects.filter(is_active=True).order_by('-created_at')

    def list(self, request, *args, **kwargs):
        cache_key = 'home:skill_list'
        cached_data = cache.get(cache_key)
        if cached_data:
            return Response(cached_data)

        response = super().list(request, *args, **kwargs)
        cache.set(cache_key, response.data, timeout=CACHE_TTL_SECONDS)
        return response


class KnowledgeListView(ListAPIView):
    permission_classes = [ReadOnly]
    serializer_class = KnowledgeSerializer

    def get_queryset(self):
        return Knowledge.objects.filter(is_active=True).order_by('-created_at')

    def list(self, request, *args, **kwargs):
        cache_key = 'home:knowledge_list'
        cached_data = cache.get(cache_key)
        if cached_data:
            return Response(cached_data)

        response = super().list(request, *args, **kwargs)
        cache.set(cache_key, response.data, timeout=CACHE_TTL_SECONDS)
        return response


class HomeBundleView(APIView):
    permission_classes = [ReadOnly]

    def get(self, request):
        try:
            cache_key = 'home:bundle:v1'
            cached_data = cache.get(cache_key)
            if cached_data:
                return Response(cached_data)

            home = Home.objects.filter(is_active=True).first()
            aboutme = AboutMe.objects.filter(is_active=True).first()
            services_title = MyServiceTitle.objects.filter(is_active=True).first()
            resume = MyResume.objects.filter(is_active=True).first()
            menu = MainMenu.objects.filter(is_active=True).first()

            services = MyService.objects.filter(is_active=True).order_by('-created_at')
            education = Education.objects.filter(is_active=True).order_by('-created_at')
            experience = Experience.objects.filter(is_active=True).order_by('-created_at')
            skills = Skill.objects.filter(is_active=True).order_by('-created_at')
            knowledge = Knowledge.objects.filter(is_active=True).order_by('-created_at')

            payload = {
                "home": HomeSerializer(home).data if home else None,
                "about_me": AboutMeSerializer(aboutme).data if aboutme else None,
                "service_title": MyServiceTitleSerializer(services_title).data if services_title else None,
                "resume": MyResumeSerializer(resume, context={"request": request}).data if resume else None,
                "main_menu": MainMenuSerializer(menu).data if menu else None,
                "services": MyServiceSerializer(services, many=True).data,
                "education": EducationSerializer(education, many=True).data,
                "experience": ExperienceSerializer(experience, many=True).data,
                "skills": SkillSerializer(skills, many=True).data,
                "knowledge": KnowledgeSerializer(knowledge, many=True).data,
            }

            cache.set(cache_key, payload, timeout=CACHE_TTL_SECONDS)
            return Response(payload)
        except Exception as e:
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class MainMenuDetailView(APIView):
    permission_classes = [ReadOnly]

    def get(self, request):
        try:
            cache_key = 'home:active_menu'
            cached_data = cache.get(cache_key)

            if cached_data:
                return Response(cached_data)

            # Cache'de yoksa veritabanından al
            menu = MainMenu.objects.filter(is_active=True).first()
            if menu:
                serializer = MainMenuSerializer(menu)
                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)
