from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from django.http import JsonResponse

from general.utilidades.acciones import LogService
from .acciones import getData


class PromocionObtener(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        path = '/promociones/obtener/'

        # --- LOG: inicio de la petición ---
        log_id = LogService.gestionar_log(self, request, path=path)

        try:
            # --- BLOQUE 2: limpieza y validación del body ---
            data = request.data
            status = 100
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_request=data, status_code=status)

            params = {'id': data.get('id'), 'activo': data.get('activo')}

        except Exception as error:
            response = {'body': {'data': [], 'error': str(error)}, 'mensaje': str(error)}
            status = 400
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_response=response, status_code=status)
            return JsonResponse(response, status=status, safe=False)

        try:
            # --- BLOQUE 3: llamada a la acción ---
            resultado = getData(params)
            response = resultado
            status = 200
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_response=response, status_code=status)
            return JsonResponse(response, safe=False, status=status)

        except Exception as error:
            response = {'body': {'data': [], 'error': str(error)}, 'error': str(error)}
            status = 500
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_response=response, status_code=status)
            return JsonResponse(response, status=status, safe=False)
