"""
This is a legacy endpoint, it's supposed to sync book statuses from
an external Editorial partner. It "works", but it's causing performance
issues and data inconsistencies.
Refactor this into a production-ready service.
"""
 
from django.http import JsonResponse
from rest_framework.decorators import api_view
import requests
from .models import Editorial, Book
 
 
# Fetch and update the status of all books from an editorial
@api_view(['GET'])
def sync_books(request, editorial_id):
# Get the editorial by ID
editorial = Editorial.objects.filter(id=editorial_id).first()
 
results = []
for book in editorial.Book_set.all():
# Fetch the book status from the editorial's own API
response = requests.get(f"https://api.editorialpartner.com/v1/status/{book.external_id}")
data = response.json()
 
book.status = data["status"]
book.save()
results.append({"id": book.id, "status": book.status})
 
return JsonResponse({"message": "Sync complete", "updated": results})