o
    #j                     @   s   d Z ddlZddlZddlmZmZmZmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ defd	d
ZdefddZdefddZdS )z{
Global Flask error handling middleware
Provides centralized error handling for the Flask API with Laravel-style responses
    N)Flaskrequestjsonifyg)HTTPException)ValidationException)ApiResponse)
get_loggerappc                    s   t d tdtffdd} dfdd} dfd	d
} dfdd} dfdd} dfdd} dfdd} d fdd} tdtffdd}	 tdtf fdd}
dS )zu
    Register global error handlers for the Flask application

    Args:
        app: Flask application instance
    error_handlerec                    s*     d| j d| j  t| j| jS )z<Handle ValidationException and return Laravel-style responsezValidation error: z - Errors: )warningmessageerrorsr   validation_errorr   logger :/var/www/html/oms-prod-mcp/app/middleware/error_handler.pyhandle_validation_exception   s   z<register_error_handlers.<locals>.handle_validation_exception  c                    "     dt|   tjdddS )zHandle 400 Bad Request errorszBad request: z.Bad request. Please check your request format.r   status_coder   strr   errorr   r   r   r   handle_bad_request      z3register_error_handlers.<locals>.handle_bad_request  c                    r   )zHandle 401 Unauthorized errorszUnauthorized access attempt: z>Unauthorized. Please provide valid authentication credentials.r    r   r   r   r   r   r   handle_unauthorized$   r   z4register_error_handlers.<locals>.handle_unauthorized  c                    r   )zHandle 403 Forbidden errorszForbidden access attempt: z=Forbidden. You don't have permission to access this resource.r"   r   r   r   r   r   r   handle_forbidden*   r   z1register_error_handlers.<locals>.handle_forbidden  c                          dtj  tjdddS )zHandle 404 Not Found errorszResource not found: z%The requested resource was not found.r$   r   )r   r   urlr   r   r   r   r   r   handle_not_found0      z1register_error_handlers.<locals>.handle_not_found  c                    s(     dtj dtj  tjdddS )z$Handle 405 Method Not Allowed errorszMethod not allowed:  z%Method not allowed for this endpoint.r)   r   )r   r   methodr&   r   r   r   r   r   r   handle_method_not_allowed6   s   z:register_error_handlers.<locals>.handle_method_not_allowed  c                    r%   )z#Handle 429 Too Many Requests errorszRate limit exceeded: z*Too many requests. Please try again later.r-   r   )r   r   remote_addrr   r   r   r   r   r   handle_too_many_requests<   r(   z9register_error_handlers.<locals>.handle_too_many_requests  c                    s^    dt|    t   jdr(tj dt|  dt  ddS tj dddS )z5Handle 500 Internal Server Error - Always return JSONzInternal server error: DEBUG

Traceback:
r0   r   z"An internal server error occurred.r   r   	traceback
format_excconfiggetr   r   r
   r   r   r   handle_internal_server_errorB      z=register_error_handlers.<locals>.handle_internal_server_errorc                    s0     d| j d| j  tj| jpd| jdS )z3Handle generic HTTP exceptions - Always return JSONzHTTP exception: z - zAn error occurred.r   )r   codedescriptionr   r   r   r   r   r   handle_http_exceptionQ   s   z6register_error_handlers.<locals>.handle_http_exceptionc                    s^    dt|    t   jdr(tj dt|  dt  ddS tj dddS )z4Handle any unhandled exceptions - Always return JSONzUnhandled exception: r1   zUnhandled error: r2   r0   r   zAn unexpected error occurred.r3   r   r8   r   r   handle_generic_exceptionW   r:   z9register_error_handlers.<locals>.handle_generic_exceptionN)r	   errorhandlerr   r   	Exception)r
   r   r   r!   r#   r'   r,   r/   r9   r=   r>   r   r8   r   register_error_handlers   s*   rA   c                    sF   t d j fdd} j fdd} jfdd}dS )	zz
    Register request lifecycle handlers for the Flask application

    Args:
        app: Flask application instance
    request_handlerc                     sx    j dr8dtj dtj  tjrtjddnd} | r(d|   tjr:dt	tj  dS dS dS )	z;Run before each request for additional validation and setupr1   z	Request: r*   T)silentNzJSON Body: zQuery Params: )
r6   r7   debugr   r+   r&   is_jsonget_jsonargsdict)	json_bodyr8   r   r   before_request_validationp   s   z<register_request_handlers.<locals>.before_request_validationc              
      s   d| j d< d| j d< d| j d<  jddr%d	| j d
< d| j d< d| j d< | jdkru| jsu| jdsuz&d|  r?| jddnd| jd}t	|| _
d| _d| j  W | S  tyt } zd|  W Y d}~| S d}~ww | S )z'Ensure all responses are JSON formattednosniffzX-Content-Type-OptionsDENYzX-Frame-Optionsz1; mode=blockzX-XSS-ProtectionENABLE_CORST*zAccess-Control-Allow-OriginzGET, POST, PUT, DELETE, OPTIONSzAccess-Control-Allow-MethodszContent-Type, AuthorizationzAccess-Control-Allow-Headersr   zapplication/jsonzAn error occurred)as_textzUnknown error)r   r   r   z+Converted non-JSON error response to JSON: z$Failed to convert response to JSON: N)headersr6   r7   r   rE   content_type
startswithget_datajsondumpsdatar   r@   r   )response
error_datar   r8   r   r   ensure_json_response~   s0   






z7register_request_handlers.<locals>.ensure_json_responsec                    s&     d| j dtj dtj  | S )z"Run after each request for cleanupz
Response: z for r*   )rD   r   r   r+   r&   )rW   r   r   r   after_request_cleanup   s   "z8register_request_handlers.<locals>.after_request_cleanupN)r	   before_requestafter_request)r
   rJ   rY   rZ   r   r8   r   register_request_handlersg   s    r]   c                 C   s   t |  t|  dS )zp
    Complete error handling setup for Flask application

    Args:
        app: Flask application instance
    N)rA   r]   )r
   r   r   r   setup_error_handling   s   r^   )__doc__r4   rT   flaskr   r   r   r   werkzeug.exceptionsr   #app.exceptions.validation_exceptionr   app.utils.response_helperr   app.utils.helpersr	   rA   r]   r^   r   r   r   r   <module>   s    XA