"""API endpoints for the RisingCompute marketing site."""
from __future__ import annotations

from django.conf import settings
from django.core.mail import send_mail
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import BlogPost, Founder, JobOpening, Product
from .serializers import (
    BlogPostDetailSerializer,
    BlogPostListSerializer,
    ContactSubmissionSerializer,
    FounderSerializer,
    JobApplicationSerializer,
    JobOpeningSerializer,
    NewsletterSignupSerializer,
    ProductSerializer,
)


def _client_ip(request) -> str | None:
    forwarded = request.META.get("HTTP_X_FORWARDED_FOR", "")
    if forwarded:
        return forwarded.split(",")[0].strip()
    return request.META.get("REMOTE_ADDR")


# --------------------------------------------------------------------------- #
# Read endpoints — content for the public site
# --------------------------------------------------------------------------- #
class ProductListView(generics.ListAPIView):
    serializer_class = ProductSerializer
    queryset = Product.objects.filter(is_published=True)


class ProductDetailView(generics.RetrieveAPIView):
    serializer_class = ProductSerializer
    queryset = Product.objects.filter(is_published=True)
    lookup_field = "slug"


class FounderListView(generics.ListAPIView):
    serializer_class = FounderSerializer
    queryset = Founder.objects.filter(is_published=True)


class BlogPostListView(generics.ListAPIView):
    serializer_class = BlogPostListSerializer
    queryset = BlogPost.objects.filter(is_published=True)


class BlogPostDetailView(generics.RetrieveAPIView):
    serializer_class = BlogPostDetailSerializer
    queryset = BlogPost.objects.filter(is_published=True)
    lookup_field = "slug"


class JobOpeningListView(generics.ListAPIView):
    serializer_class = JobOpeningSerializer
    queryset = JobOpening.objects.filter(is_open=True)


# --------------------------------------------------------------------------- #
# Write endpoints — form submissions
# --------------------------------------------------------------------------- #
class ContactSubmissionView(APIView):
    """Accepts a contact / evaluation request from the website."""

    def post(self, request):
        serializer = ContactSubmissionSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        submission = serializer.save(
            user_agent=request.META.get("HTTP_USER_AGENT", "")[:400],
            ip_address=_client_ip(request),
        )

        try:
            send_mail(
                subject=f"[risingcompute.in] New enquiry — {submission.get_interest_display()}",
                message=(
                    f"From: {submission.name} <{submission.email}>\n"
                    f"Company: {submission.company}\n"
                    f"Role: {submission.role}\n"
                    f"Country: {submission.country}\n"
                    f"Interest: {submission.get_interest_display()}\n"
                    f"Referrer: {submission.referrer}\n\n"
                    f"Message:\n{submission.message}\n"
                ),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[settings.NOTIFY_EMAIL_TO],
                fail_silently=True,
            )
        except Exception:
            # Never let an email hiccup break the submission flow.
            pass

        return Response(
            {"ok": True, "message": "Thanks — we'll be in touch shortly."},
            status=status.HTTP_201_CREATED,
        )


class NewsletterSignupView(APIView):
    def post(self, request):
        serializer = NewsletterSignupSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(
            {"ok": True, "message": "You're on the list."},
            status=status.HTTP_201_CREATED,
        )


class JobApplicationView(APIView):
    def post(self, request):
        serializer = JobApplicationSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(
            {"ok": True, "message": "Application received — we'll be in touch."},
            status=status.HTTP_201_CREATED,
        )


# --------------------------------------------------------------------------- #
# Health check
# --------------------------------------------------------------------------- #
class HealthView(APIView):
    """Simple uptime check used by deploy / monitoring."""

    def get(self, request):
        return Response({"status": "ok", "service": "risingcompute-api"})
