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 ejecutarAutomatizaciones, getHistorial, getEstado


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

    def post(self, request):
        path = '/automatizados/ejecutar/'

        # --- BLOQUE 1: Inicio Log ---
        log_id = LogService.gestionar_log(self, request, path=path)

        try:
            # --- BLOQUE 2: Data Cleaning ---
            data = request.data
            status = 100
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_request=data, status_code=status)

            params = {
                'nombre': data.get('nombre'),
                'descripcion': data.get('descripcion'),
                'origen': data.get('origen') or 'manual',
            }

        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: Action Call ---
            resultado = ejecutarAutomatizaciones(params)
            response = resultado
            status = 200
            # --- BLOQUE 4: Cierre Log ---
            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)


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

    def post(self, request):
        path = '/automatizados/historial/'

        # --- BLOQUE 1: Inicio Log ---
        log_id = LogService.gestionar_log(self, request, path=path)

        try:
            # --- BLOQUE 2: Data Cleaning ---
            data = request.data
            status = 100
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_request=data, status_code=status)

            params = {
                'estado': data.get('estado'),
                'limit': data.get('limit') or 20,
            }

        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: Action Call ---
            resultado = getHistorial(params)
            response = resultado
            status = 200
            # --- BLOQUE 4: Cierre Log ---
            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)


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

    def post(self, request):
        path = '/automatizados/estado/'

        # --- BLOQUE 1: Inicio Log ---
        log_id = LogService.gestionar_log(self, request, path=path)

        try:
            # --- BLOQUE 2: Data Cleaning ---
            data = request.data
            status = 100
            LogService.gestionar_log(self, request, log_id=log_id, path=path, body_request=data, status_code=status)

        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: Action Call ---
            resultado = getEstado()
            response = resultado
            status = 200
            # --- BLOQUE 4: Cierre Log ---
            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)
