import logging

from rest_framework import viewsets, status, generics, mixins
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.exceptions import PermissionDenied as DRFPermissionDenied
from rest_framework.response import Response
from django.db.models import F, Prefetch, Q, Sum
from django.db import transaction
from django.core.mail import send_mail
from django.http import HttpResponse
from django.conf import settings
from django.utils import timezone
from .models import (Author, Book, BookRight, CartItem, Catalog, Category, ContactSubmission, FounderAchievement, FounderParagraph, HomePageContent, Order, OrderItem, RightsAgencyFeature, RightsType, Service, Testimonial, FooterQuickLink, FooterServiceItem, Subscriber, DistributionPackage, AuthorApplication, AuthorApplicationBook, LegacyAuthorInvitation)
# store.Order/OrderItem is the real, active order system (store.urls is
# mounted ahead of catalog_app.urls in rights_catalog/urls.py for
# cart/checkout/orders) — aliased to avoid clashing with catalog_app's own
# (legacy, shadowed) Order model imported above.
from store.models import Order as StoreOrder
from .serializers import (CatalogSerializer, CategorySerializer, AuthorSerializer, RightsTypeSerializer,
                          BookListSerializer, BookDetailSerializer, BookRightSerializer, CartItemSerializer, HomePageContentSerializer, ServiceSerializer, FounderParagraphSerializer, FounderAchievementSerializer, RightsAgencyFeatureSerializer, TestimonialSerializer, ContactSubmissionSerializer,
                          OrderSerializer, OrderItemSerializer, AuthorDetailSerializer, SubscriberSerializer,
                          DistributionPackageSerializer, AuthorApplicationSerializer, AuthorApplicationBookCoverSerializer,
                          AgreementPreviewSerializer, LegacyInvitationDetailSerializer, LegacyInvitationSubmitSerializer,
                          LegacyAgreementPreviewSerializer, LegacyInvitationBookEditSerializer)
from .permissions import IsAdminOrReadOnly, IsAdminUser
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken


@api_view(['POST'])
@permission_classes([AllowAny])
def register_user(request):
    """
    Register a new user.
    """
    username = request.data.get('username')
    email = request.data.get('email')
    password = request.data.get('password')

    if not username or not password:
        return Response({'error': 'Username and password are required'}, status=status.HTTP_400_BAD_REQUEST)

    if User.objects.filter(username=username).exists():
        return Response({'error': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST)

    user = User.objects.create_user(username=username, email=email, password=password)
    user.save()

    # Issue JWT tokens upon registration
    refresh = RefreshToken.for_user(user)
    return Response({
        'message': 'User registered successfully',
        'refresh': str(refresh),
        'access': str(refresh.access_token)
    }, status=status.HTTP_201_CREATED)

# Catalogs, categories, rights types
class CatalogViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Catalog.objects.all()
    serializer_class = CatalogSerializer

class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

class RightsTypeViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = RightsType.objects.all()
    serializer_class = RightsTypeSerializer

class AuthorViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return AuthorDetailSerializer
        return AuthorSerializer

    def get_object(self):
        # Accepts either the numeric pk (old links already shared, e.g.
        # /api/authors/16/) or the slug (new canonical URLs) — whichever was
        # passed in the URL. Same pattern as BookViewSet.get_object.
        queryset = self.filter_queryset(self.get_queryset())
        lookup_value = self.kwargs[self.lookup_url_kwarg or self.lookup_field]
        if lookup_value.isdigit():
            obj = get_object_or_404(queryset, pk=lookup_value)
        else:
            obj = get_object_or_404(queryset, slug=lookup_value)
        self.check_object_permissions(self.request, obj)
        return obj

# Books: search, list, detail
class BookViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Book.objects.filter(is_listed=True).select_related('author','publisher','catalog','category').prefetch_related(
        'available_languages', 
        'available_formats',
        'platform_links__platform',
        Prefetch('book_rights', queryset=BookRight.objects.filter(status='AVAILABLE').select_related('rights_type'), to_attr='available_book_rights')
    )
    serializer_class = BookListSerializer

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return BookDetailSerializer
        return BookListSerializer

    def get_object(self):
        # Accepts either the numeric pk (old links already shared, e.g.
        # /api/books/16/) or the slug (new canonical URLs) — whichever was
        # passed in the URL. Keeps every existing link/integration working
        # unchanged while enabling slug-based lookups going forward.
        queryset = self.filter_queryset(self.get_queryset())
        lookup_value = self.kwargs[self.lookup_url_kwarg or self.lookup_field]
        if lookup_value.isdigit():
            obj = get_object_or_404(queryset, pk=lookup_value)
        else:
            obj = get_object_or_404(queryset, slug=lookup_value)
        self.check_object_permissions(self.request, obj)
        return obj

    def list(self, request, *args, **kwargs):
        q = request.query_params.get('q')
        category = request.query_params.get('category')
        rights = request.query_params.get('rights')
        catalog = request.query_params.get('catalog')
        featured = request.query_params.get('featured')
        qs = self.get_queryset()

        if catalog:
            qs = qs.filter(catalog__slug=catalog) if not catalog.isdigit() else qs.filter(catalog__id=catalog)
        if category:
            qs = qs.filter(category__slug=category) if not category.isdigit() else qs.filter(category__id=category)
        if rights:
            # filter by rights type code or id
            if rights.isdigit():
                qs = qs.filter(book_rights__rights_type__id=int(rights))
            else:
                qs = qs.filter(book_rights__rights_type__code__iexact=rights)
        if q:
            qs = qs.filter(
                Q(title__icontains=q) | Q(subtitle__icontains=q) | Q(description__icontains=q)
                | Q(author__name__icontains=q) | Q(publisher__name__icontains=q)
            ).distinct()

        if featured:
            qs = qs.filter(is_featured=True)

        page = self.paginate_queryset(qs)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(qs, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def bestsellers(self, request):
        """
        Real best-sellers, ranked by total quantity sold across completed
        store orders (store.OrderItem, joined via the store_order_items
        related_name) — not a relabeled `is_featured` flag. Books with no
        completed sales are excluded rather than padded in, so this list is
        empty until the store has real order history.
        """
        try:
            limit = int(request.query_params.get('limit', 10))
        except ValueError:
            limit = 10
        completed_statuses = [
            StoreOrder.STATUS_PAID,
            StoreOrder.STATUS_PROCESSING,
            StoreOrder.STATUS_SHIPPED,
            StoreOrder.STATUS_DELIVERED,
        ]
        qs = self.get_queryset().filter(
            store_order_items__order__status__in=completed_statuses
        ).annotate(
            units_sold=Sum(
                'store_order_items__quantity',
                filter=Q(store_order_items__order__status__in=completed_statuses),
            )
        ).filter(units_sold__gt=0).order_by('-units_sold')[:limit]
        serializer = self.get_serializer(qs, many=True)
        return Response(serializer.data)

# Admin: create / update books & book rights
class AdminBookViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = Book.objects.all()
    serializer_class = BookDetailSerializer

# Cart endpoints
class CartItemViewSet(viewsets.ModelViewSet):
    serializer_class = CartItemSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return CartItem.objects.filter(user=self.request.user).select_related('book_right__book','book_right__rights_type')

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

# Checkout
from rest_framework.views import APIView

class CheckoutView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        with transaction.atomic():
            # lock cart items
            cart_items = CartItem.objects.select_for_update().filter(user=user).select_related('book_right')
            if not cart_items.exists():
                return Response({'error':'Cart is empty'}, status=status.HTTP_400_BAD_REQUEST)

            total = 0
            # Validate
            for item in cart_items:
                br = BookRight.objects.select_for_update().get(pk=item.book_right.pk)
                if br.status != 'AVAILABLE':
                    return Response({'error': f'Right {br.id} not available'}, status=status.HTTP_400_BAD_REQUEST)
                if br.exclusive and br.status == 'SOLD':
                    return Response({'error': f'Exclusive right {br.id} already sold'}, status=status.HTTP_400_BAD_REQUEST)
                if br.available_quantity is not None and br.available_quantity < item.quantity:
                    return Response({'error': f'Insufficient quantity for right {br.id}'}, status=status.HTTP_400_BAD_REQUEST)
                total += float(br.price) * item.quantity

            order = Order.objects.create(user=user, total_amount=total, currency='USD', status='PENDING')

            for item in cart_items:
                br = BookRight.objects.select_for_update().get(pk=item.book_right.pk)
                # create order item snapshot
                snapshot = {
                    'book_title': br.book.title,
                    'rights_type': br.rights_type.code,
                    'exclusive': br.exclusive,
                }
                OrderItem.objects.create(
                    order=order,
                    book_right=br,
                    unit_price=br.price,
                    quantity=item.quantity,
                    total_price=br.price * item.quantity,
                    rights_snapshot=snapshot
                )

                # Update inventory/status
                if br.exclusive:
                    br.status = 'SOLD'
                    br.save(update_fields=['status','updated_at'])
                elif br.available_quantity is not None:
                    br.available_quantity = F('available_quantity') - item.quantity
                    br.save()
                    # refresh from db to check new value
                    br.refresh_from_db()
                    if br.available_quantity <= 0:
                        br.status = 'SOLD'
                        br.save(update_fields=['status','updated_at'])

            # clear cart
            cart_items.delete()

            serializer = OrderSerializer(order)
            return Response({'order': serializer.data}, status=status.HTTP_201_CREATED)

class ContactSubmissionView(generics.CreateAPIView):
    queryset = ContactSubmission.objects.all()
    serializer_class = ContactSubmissionSerializer
    permission_classes = [AllowAny]

    def perform_create(self, serializer):
        instance = serializer.save()

        # Send an email notification
        try:
            home_content = HomePageContent.objects.filter(is_active=True).first()
            if home_content and home_content.contact_email:
                subject = f"New Contact Submission: {instance.subject}"
                message_body = f"""
You have received a new message from your website's contact form.

Details:
- Name: {instance.first_name} {instance.last_name}
- Email: {instance.email}
- Subject: {instance.subject}

Message:
{instance.message}
"""
                send_mail(
                    subject=subject,
                    message=message_body,
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[home_content.contact_email],
                    fail_silently=False,  # In production, you might want to set this to True
                )
        except Exception:
            # Log the error but don't fail the request
            logging.getLogger(__name__).exception("Error sending contact submission email")

class NewsletterSubscriptionView(generics.CreateAPIView):
    queryset = Subscriber.objects.all()
    serializer_class = SubscriberSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        from catalog_app.services.newsletter_service import send_welcome_email

        email = request.data.get('email')
        if email:
            # Check if exists (even if inactive)
            subscriber = Subscriber.objects.filter(email=email).first()
            if subscriber:
                if not subscriber.is_active:
                    subscriber.is_active = True
                    subscriber.save()
                    send_welcome_email(subscriber)
                    return Response({'message': 'Subscribed successfully!'}, status=status.HTTP_200_OK)
                return Response({'message': 'Already subscribed.'}, status=status.HTTP_200_OK)
        response = super().create(request, *args, **kwargs)
        if response.status_code == status.HTTP_201_CREATED and email:
            new_subscriber = Subscriber.objects.filter(email=email).first()
            if new_subscriber:
                send_welcome_email(new_subscriber)
        return response

@api_view(['GET'])
@permission_classes([AllowAny])
def unsubscribe_newsletter(request, token):
    subscriber = get_object_or_404(Subscriber, token=token)
    if subscriber.is_active:
        subscriber.is_active = False
        subscriber.save()
        return HttpResponse('<div style="text-align:center; margin-top:50px; font-family:sans-serif;"><h1>Unsubscribed</h1><p>You have been successfully unsubscribed from our newsletter.</p></div>')
    return HttpResponse('<div style="text-align:center; margin-top:50px; font-family:sans-serif;"><h1>Unsubscribed</h1><p>You are already unsubscribed.</p></div>')

class HomePageContentView(APIView):
    """
    Provides the content for the website's home page hero section.
    """
    permission_classes = [AllowAny]

    def get(self, request, format=None):
        try:
            # Get the single active home page content
            content = HomePageContent.objects.prefetch_related('navigation_items', 'services', 'founder_paragraphs', 'founder_achievements', 'rights_agency_features', 'testimonials', 'footer_quick_links', 'footer_service_items').get(is_active=True)
            serializer = HomePageContentSerializer(content, context={'request': request})
            return Response(serializer.data)
        except HomePageContent.DoesNotExist:
            # Return a default or empty response if no active content is set
            return Response({
                'title': 'Welcome to Tai AfroPress',
                'navigation_items': [
                    {'label': 'Home', 'href': '/#home'},
                    {'label': 'Books', 'href': '/#books'},
                    {'label': 'Our Services', 'href': '/#about'},
                    {'label': 'Rights Catalog', 'href': '/#rights'},
                    {'label': 'Contact Us', 'href': '/#contact'},
                ],
                'subtitle': 'Your catalog for African literature rights.',
                'background_image': None,
                'button_text': 'Get Started',
                'about_title_start': 'About',
                'about_title_end': 'Us',
                'about_description': 'We connect African publishers with global markets.',
                'services_title_start': 'Our',
                'services_title_end': 'Services',
                'services_description': 'We offer a range of services to help you succeed.',
                'services': [],
                'founder_headline_start': 'Meet the',
                'founder_headline_end': 'Founder',
                'founder_title': 'A Passion for African Stories',
                'founder_image': None,
                'founder_paragraphs': [],
                'founder_achievements': [],
                'rights_agency_headline_start': 'Rights Agency',
                'rights_agency_headline_end': 'Global Connections',
                'rights_agency_description': 'Our extensive network of international publishers, agents, and literary scouts ensures African stories find their perfect global homes. We specialize in rights buying and selling collaborations that respect cultural authenticity while maximizing global reach.',
                'rights_agency_button_text': 'Explore Catalog',
                'rights_agency_image': None,
                'rights_agency_features': [],
                'testimonials_title_start': 'Author',
                'testimonials_title_end': 'Success Stories',
                'testimonials_description': 'Hear from African authors who have successfully reached global audiences through our guidance.',
                'testimonials': [],
                'contact_title_start': 'Get',
                'contact_title_end': 'In Touch',
                'contact_description': "Ready to take your African story to the world? Let's discuss how we can help you achieve your publishing goals.",
                'contact_email': 'hello@taiafropress.com',
                'contact_phone': '+254 700 123 456',
                'contact_address': 'Nairobi, Kenya',
                'contact_facebook_url': '#',
                'contact_instagram_url': '#',
                'contact_linkedin_url': '#',
                'contact_twitter_url': '#',
                'newsletter_title': 'Author Tips Newsletter',
                'newsletter_description': 'Get weekly insights on African literature, publishing trends, and author success strategies.',
                'footer_brand_name': 'Tai AfroPress',
                'footer_description': 'Empowering African authors to share their stories with the world through professional publishing consultancy and global rights management.',
                'footer_quick_links_title': 'Quick Links',
                'footer_services_title': 'Services',
                'footer_copyright_text': '© 2025 Tai AfroPress. All rights reserved. Empowering African stories for the world.',
                'footer_quick_links': [
                    {'text': 'About Us', 'url': '#about'},
                    {'text': 'Services', 'url': '#services'},
                    {'text': 'Rights Agency', 'url': '#rights'},
                    {'text': 'Meet the Founder', 'url': '#founder'},
                ],
                'footer_service_items': [
                    {'text': 'Manuscript Editing'},
                    {'text': 'Cover Design'},
                    {'text': 'Book Layout'},
                    {'text': 'Rights Management'},
                ],
            })
        except HomePageContent.MultipleObjectsReturned:
            # This case should be prevented by the model's save method, but as a fallback:
            content = HomePageContent.objects.prefetch_related('navigation_items', 'services', 'founder_paragraphs', 'founder_achievements', 'rights_agency_features', 'testimonials', 'footer_quick_links', 'footer_service_items').filter(is_active=True).order_by('-updated_at').first()
            serializer = HomePageContentSerializer(content, context={'request': request})
            return Response(serializer.data)


# ===========================================================================
# Author distribution applications
# ===========================================================================

class DistributionPackageListView(generics.ListAPIView):
    """GET /api/distribution-packages/ — active packages, public."""
    queryset = DistributionPackage.objects.filter(is_active=True).order_by('tier')
    serializer_class = DistributionPackageSerializer
    permission_classes = [AllowAny]


class AuthorApplicationCreateView(generics.CreateAPIView):
    """
    POST /api/author-applications/
    Public submission: package + profile + payment details + signature +
    books[]. Creates nothing beyond the AuthorApplication/AuthorApplicationBook
    rows — an admin must approve it before a real Author/Book exists (see
    catalog_app/services/author_application_service.py).
    """
    queryset = AuthorApplication.objects.all()
    serializer_class = AuthorApplicationSerializer
    permission_classes = [AllowAny]

    def perform_create(self, serializer):
        from catalog_app.services.agreement_service import render_agreement
        from catalog_app.services.notification_service import notify_admins_of_new_application

        forwarded = self.request.META.get('HTTP_X_FORWARDED_FOR', '')
        ip = forwarded.split(',')[0].strip() if forwarded else self.request.META.get('REMOTE_ADDR')
        signed_at = timezone.now()
        application = serializer.save(signed_at=signed_at, signed_ip_address=ip or None)

        # Rendered server-side from the application's own saved data (never
        # trusted from the client) so the stored snapshot is genuinely proof
        # of what was agreed to, not just whatever text a client claims it saw.
        application.agreement_text_snapshot = render_agreement(application=application, today=signed_at.date())
        application.save(update_fields=['agreement_text_snapshot'])

        # Best-effort — a mail hiccup shouldn't fail the applicant's
        # submission (fail_silently=True inside notify_admins_of_new_application).
        notify_admins_of_new_application(application)


class AgreementPreviewView(APIView):
    """
    POST /api/author-applications/preview-agreement/
    Renders the full agreement text from package + profile + payment + books
    WITHOUT saving anything, so the wizard can show the applicant exactly
    what they're about to sign before they reach the final submit step.
    """
    permission_classes = [AllowAny]

    def post(self, request):
        from catalog_app.services.agreement_service import render_agreement

        serializer = AgreementPreviewSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = dict(serializer.validated_data)
        books_data = data.pop('books')

        application = AuthorApplication(**data)
        books = [AuthorApplicationBook(**b) for b in books_data]
        text = render_agreement(application=application, books=books)
        return Response({'agreement_text': text})


class AuthorApplicationBookCoverUploadView(generics.UpdateAPIView):
    """
    PATCH /api/author-applications/books/<id>/cover/
    Separate single-file upload for a submitted book's cover, called after
    the main application POST — keeps the initial submission as plain JSON
    instead of a nested multipart payload. Only works while the application
    is still pending (locked once reviewed).
    """
    queryset = AuthorApplicationBook.objects.filter(application__status=AuthorApplication.STATUS_PENDING)
    serializer_class = AuthorApplicationBookCoverSerializer
    permission_classes = [AllowAny]
    parser_classes = [MultiPartParser, FormParser]
    http_method_names = ['patch']


# ---------------------------------------------------------------------------
# Legacy author invitations (retroactive agreement signing)
# ---------------------------------------------------------------------------

def _get_legacy_invitation_or_404(token):
    invitation = get_object_or_404(LegacyAuthorInvitation, token=token)
    return invitation


class LegacyInvitationDetailView(APIView):
    """
    GET /api/legacy-invitations/<uuid:token>/
    Public (token-gated, not guessable) — fetches everything the signing
    wizard needs: the author's current known data (to pre-fill), the fixed
    list of books this invitation covers, and status/expiry.
    """
    permission_classes = [AllowAny]

    def get(self, request, token):
        invitation = _get_legacy_invitation_or_404(token)
        return Response(LegacyInvitationDetailSerializer(invitation, context={"request": request}).data)


class LegacyInvitationBookEditView(generics.UpdateAPIView):
    """
    PATCH /api/legacy-invitations/<uuid:token>/books/<int:book_id>/
    Stage a title/cover/price change for one of this invitation's books —
    applied to the real Book only on admin approval (see
    legacy_invitation_service.approve_invitation). Only allowed while the
    invitation hasn't been submitted yet. Blank/omitted fields mean "no
    change requested" for that field.
    """
    serializer_class = LegacyInvitationBookEditSerializer
    permission_classes = [AllowAny]
    parser_classes = [MultiPartParser, FormParser]
    http_method_names = ['patch']

    def get_object(self):
        from catalog_app.models import LegacyInvitationBookEdit

        invitation = _get_legacy_invitation_or_404(self.kwargs['token'])
        if invitation.status not in (LegacyAuthorInvitation.STATUS_SENT, LegacyAuthorInvitation.STATUS_DRAFT):
            raise DRFPermissionDenied("This invitation can no longer be edited.")
        book = get_object_or_404(invitation.books, pk=self.kwargs['book_id'])
        edit, _ = LegacyInvitationBookEdit.objects.get_or_create(invitation=invitation, book=book)
        return edit


class LegacyInvitationPreviewView(APIView):
    """
    POST /api/legacy-invitations/<uuid:token>/preview-agreement/
    Renders the full agreement text from package + profile + payment +
    the invitation's books (any pending title/price edits included) WITHOUT
    saving anything — mirrors AgreementPreviewView.
    """
    permission_classes = [AllowAny]

    def post(self, request, token):
        from catalog_app.services.legacy_invitation_service import effective_books, render_legacy_agreement

        invitation = _get_legacy_invitation_or_404(token)
        if invitation.status not in (LegacyAuthorInvitation.STATUS_SENT, LegacyAuthorInvitation.STATUS_DRAFT):
            return Response({"error": "This invitation has already been submitted."}, status=status.HTTP_400_BAD_REQUEST)
        if invitation.is_expired:
            return Response({"error": "This link has expired. Ask Tai AfroPress to resend it."}, status=status.HTTP_410_GONE)

        serializer = LegacyAgreementPreviewSerializer(instance=invitation, data=request.data)
        serializer.is_valid(raise_exception=True)
        # Apply the submitted fields onto an unsaved copy — never persisted,
        # just used to render the preview text.
        preview = LegacyAuthorInvitation(author=invitation.author, **serializer.validated_data)
        text = render_legacy_agreement(invitation=preview, books=effective_books(invitation))
        return Response({'agreement_text': text})


class LegacyInvitationSubmitView(APIView):
    """
    POST /api/legacy-invitations/<uuid:token>/submit/
    The author's one-shot submission: package + profile + payment + signature.
    Books are NOT part of the payload — they were fixed by staff at creation.
    """
    permission_classes = [AllowAny]

    def post(self, request, token):
        from catalog_app.services.legacy_invitation_service import render_legacy_agreement
        from catalog_app.services.notification_service import notify_admins_of_legacy_submission

        invitation = _get_legacy_invitation_or_404(token)
        if invitation.status not in (LegacyAuthorInvitation.STATUS_SENT, LegacyAuthorInvitation.STATUS_DRAFT):
            return Response({"error": "This invitation has already been submitted."}, status=status.HTTP_400_BAD_REQUEST)
        if invitation.is_expired:
            return Response({"error": "This link has expired. Ask Tai AfroPress to resend it."}, status=status.HTTP_410_GONE)

        serializer = LegacyInvitationSubmitSerializer(instance=invitation, data=request.data)
        serializer.is_valid(raise_exception=True)

        forwarded = request.META.get('HTTP_X_FORWARDED_FOR', '')
        ip = forwarded.split(',')[0].strip() if forwarded else request.META.get('REMOTE_ADDR')
        signed_at = timezone.now()

        for field, value in serializer.validated_data.items():
            setattr(invitation, field, value)
        invitation.signed_at = signed_at
        invitation.signed_ip_address = ip or None
        invitation.status = LegacyAuthorInvitation.STATUS_SUBMITTED
        invitation.save()

        # Rendered server-side from the invitation's own saved data — same
        # never-trust-the-client rule as the normal application flow.
        invitation.agreement_text_snapshot = render_legacy_agreement(invitation=invitation, today=signed_at.date())
        invitation.save(update_fields=['agreement_text_snapshot'])

        notify_admins_of_legacy_submission(invitation)

        return Response(LegacyInvitationDetailSerializer(invitation).data)
