# ==============================#
# LEGAL DOCUMENT VIEWS          #
# ==============================#
import logging

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions, status

from .models import LegalDocument

logger = logging.getLogger(__name__)

VALID_TYPES = {choice[0] for choice in LegalDocument.DOC_TYPE_CHOICES}

DEFAULT_TITLES = {
    "terms": "Terms & Conditions",
    "privacy": "Privacy Policy",
}


def _doc_payload(doc):
    return {
        "doc_type": doc.doc_type,
        "title": doc.title,
        "content": doc.content,
        "is_published": doc.is_published,
        "updated_at": doc.updated_at,
    }


class LegalDocumentAdminView(APIView):
    """
    Master admin — manage platform legal documents.

    GET:  Both documents (terms + privacy), creating empty drafts if missing.
    PUT:  { doc_type, title, content, is_published } — upsert one document.
    """

    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        docs = []
        for doc_type in ("terms", "privacy"):
            doc, _ = LegalDocument.objects.get_or_create(
                doc_type=doc_type,
                defaults={"title": DEFAULT_TITLES[doc_type]},
            )
            docs.append(_doc_payload(doc))
        return Response({"documents": docs})

    def put(self, request):
        doc_type = request.data.get("doc_type")
        if doc_type not in VALID_TYPES:
            return Response(
                {"error": "doc_type must be one of: terms, privacy"},
                status=status.HTTP_400_BAD_REQUEST,
            )

        doc, _ = LegalDocument.objects.get_or_create(
            doc_type=doc_type,
            defaults={"title": DEFAULT_TITLES[doc_type]},
        )
        doc.title = request.data.get("title", doc.title) or DEFAULT_TITLES[doc_type]
        doc.content = request.data.get("content", doc.content)
        doc.is_published = bool(request.data.get("is_published", doc.is_published))
        doc.updated_by = request.user
        doc.save()

        logger.info(f"Legal document '{doc_type}' updated by {request.user.username}")
        return Response({"message": "Document saved", "document": _doc_payload(doc)})


class PublicLegalDocumentView(APIView):
    """
    Public read endpoint — GET /api/legal/<doc_type>/
    Returns the published document; used by every school panel and the
    mobile app (works before login too, e.g. on the login screen).
    """

    permission_classes = [permissions.AllowAny]
    authentication_classes = []

    def get(self, request, doc_type):
        if doc_type not in VALID_TYPES:
            return Response(
                {"error": "Unknown document type"},
                status=status.HTTP_404_NOT_FOUND,
            )
        doc = LegalDocument.objects.filter(
            doc_type=doc_type, is_published=True
        ).first()
        if not doc:
            return Response(
                {"error": "Document not available yet"},
                status=status.HTTP_404_NOT_FOUND,
            )
        return Response(_doc_payload(doc))
