from datetime import datetime
from zoneinfo import ZoneInfo

from django.utils import timezone
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Config, Guestbook, Memory
from .serializers import GuestbookCreateSerializer, MemorySerializer


class MemoryListView(ListAPIView):
    serializer_class = MemorySerializer

    def get_queryset(self):
        return (
            Memory.objects.all()
            .order_by("story_order", "id")
            .prefetch_related("photos")
        )


class GuestbookCreateView(CreateAPIView):
    queryset = Guestbook.objects.all()
    serializer_class = GuestbookCreateSerializer


class StatusView(APIView):
    def get(self, request, *args, **kwargs):
        shanghai = ZoneInfo("Asia/Shanghai")
        now = timezone.now()

        default_together = datetime(2026, 5, 4, 0, 0, 0, tzinfo=shanghai)

        config = Config.objects.filter(pk=1).first()
        if config is None:
            site_title = "Nepal Journey: Our Story"
            together_since = default_together
            unlock_at = None
        else:
            site_title = config.site_title or "Nepal Journey: Our Story"
            ts = config.together_since
            if ts is None:
                together_since = default_together
            else:
                together_since = (
                    timezone.make_aware(ts, shanghai) if timezone.is_naive(ts) else ts
                )
            ua = config.unlock_at
            if ua is None:
                unlock_at = None
            else:
                unlock_at = (
                    timezone.make_aware(ua, shanghai) if timezone.is_naive(ua) else ua
                )

        return Response(
            {
                "server_time": now,
                "unlocked": True,
                "unlock_at": unlock_at,
                "together_since": together_since,
                "site_title": site_title,
            }
        )
