o
    jh8                  
   @   s  d dl mZmZmZmZmZ d dlmZmZm	Z	m
Z
mZ d dlZd dlZd dlmZ d dlmZ eeZG dd dZdd	ed
e	e de	eeef  fddZd dededefddZd!dededefddZd"dedefddZdeeeef  defddZdS )#    )jsonifyResponsegrequestcurrent_app)DictAnyOptionalUnionListN)datetimewrapsc                   @   sP  e Zd ZdZi ZdZed>dedede	e
eef  defdd	Zed>ded
e	e dee
eef ef fddZed?ded
e	e de	e
eef  defddZed?ded
e	e de	e
eef  defddZed?ded
e	e de	e
eef  defddZed>de	e
eef  defddZed?ded
e	e de	e
eef  defddZed?ded
e	e de	e
eef  defddZed?ded
e	e de	e
eef  defddZed?de	e d
e	e de	e
eef  defddZed?ded
e	e de	e
eef  defddZed?ded
e	e de	e
eef  defdd Zed?ded
e	e de	e
eef  defd!d"Zed?ded
e	e de	e
eef  defd#d$Zed?ded
e	e de	e
eef  defd%d&Zed?ded
e	e de	e
eef  defd'd(Zed@d
edede	e
eef  defd*d+Zed@d
ed,ede	e
eef  defd-d.Ze	/	0dAd1e
ee e f d
ededefd2d3Z!edBde e d4e
eef d
e	e de	e
eef  def
d5d6Z"edBd7e e
eef  d
e	e de	e
eef  defd8d9Z#ed?de	e d
e	e de	e
eef  defd:d;Z$ed<d= Z%dS )CApiResponsez}
    High-performance API response handler for Flask applications.
    Mimics Laravel's ApiResponse trait functionality.
    i  Ndatastatus_codeheadersreturnc                 C   s|  d|  ko	dk n  }t jdd}d}|r@tt| |t|p i f}|tjv r@ttjtjk r@tj| }t	
d|  |S |dkr]t	d| d|   |d	kr]t	jd
|  dd t| trd| nd| i}d|  koqdk n  |d< t|}||_|r| D ]	\}	}
|
|j|	< qd|jd< d|jd< ttdrtj|jd< t  |jd< |r|rttjtjk r|tj|< |S )zG
        Create optimized Flask response with caching support.
             DEBUGFNzResponse cache hit for status zError response :   zServer error details: Texc_infor   successnosniffzX-Content-Type-OptionsDENYzX-Frame-Options
request_idzX-Request-IDzX-Timestamp)r   configgethashstrr   _response_cachelen_cache_max_sizeloggerdebugerror
isinstancedictr   r   itemsr   hasattrr   r   r   now	isoformat)r   r   r   should_cacheis_debug	cache_keycached_responseresponse_dataresponsekeyvalue r7   7/var/www/html/oms-prod-mcp/app/utils/response_helper.py_create_response   s8   




zApiResponse._create_responsemessagec                 C   s   |du r| S || dS )z
        Generate response body.
        When message is provided produces {"message": ..., "data": ...}.
        When omitted returns data as-is.
        N)r:   r   r7   r   r:   r7   r7   r8   _bodyQ   s   
zApiResponse._bodyc                 C      t | |}t |d|S )z_
        Send successful response (HTTP 200).
        Equivalent to PHP's ok() method.
        r   r   r<   r9   r   r:   r   r3   r7   r7   r8   ok\      zApiResponse.okc                 C   r=   )z<
        Send resource created response (HTTP 201).
           r>   r?   r7   r7   r8   createde      zApiResponse.createdc                 C   r=   )z4
        Send accepted response (HTTP 202).
           r>   r?   r7   r7   r8   acceptedm   rD   zApiResponse.acceptedc                 C   s   t i d| S )z6
        Send no content response (HTTP 204).
           r   r9   )r   r7   r7   r8   
no_contentu   s   zApiResponse.no_contentc                 C   r=   )ze
        Send bad request error (HTTP 400).
        Equivalent to PHP's badRequest() method.
        r   r>   r?   r7   r7   r8   bad_request|   rA   zApiResponse.bad_requestc                 C   r=   )zg
        Send unauthorized error (HTTP 401).
        Equivalent to PHP's unauthorize() method.
        i  r>   r?   r7   r7   r8   unauthorized   rA   zApiResponse.unauthorizedc                 C   r=   )zb
        Send forbidden error (HTTP 403).
        Equivalent to PHP's forbidden() method.
        i  r>   r?   r7   r7   r8   	forbidden   rA   zApiResponse.forbiddenc                 C   s*   | du rddi} t | |}t |d|S )za
        Send not found error (HTTP 404).
        Equivalent to PHP's notFound() method.
        Nr:   zNo data foundi  r>   r?   r7   r7   r8   	not_found   s   zApiResponse.not_foundc                 C   r=   )z;
        Send method not allowed error (HTTP 405).
        i  r>   r?   r7   r7   r8   method_not_allowed   rD   zApiResponse.method_not_allowedc                 C   r=   )z1
        Send conflict error (HTTP 409).
        i  r>   r?   r7   r7   r8   conflict   rD   zApiResponse.conflictc                 C   r=   )z3
        Send validation error (HTTP 422).
          r>   r?   r7   r7   r8   unprocessable_entity   rD   z ApiResponse.unprocessable_entityc                 C   r=   )z3
        Send rate limit error (HTTP 429).
        i  r>   r?   r7   r7   r8   too_many_requests   rD   zApiResponse.too_many_requestsc                 C   r=   )za
        Send server error (HTTP 500).
        Equivalent to PHP's serverError() method.
        r   r>   r?   r7   r7   r8   server_error   rA   zApiResponse.server_errorc                 C   r=   )z<
        Send service unavailable error (HTTP 503).
        i  r>   r?   r7   r7   r8   service_unavailable   rD   zApiResponse.service_unavailabler   c                 C      t d| i||S )z_
        Send error response with message.
        Equivalent to PHP's error() method.
        r:   rH   )r:   r   r   r7   r7   r8   r(         zApiResponse.errorcodec                 C   rU   )zp
        Send error response with fixed message.
        Equivalent to PHP's errorWithMessage() method.
        r:   rH   )r:   rW   r   r7   r7   r8   error_with_message   rV   zApiResponse.error_with_messageThe given data was invalid.rP   errorsc                 C   s   || d}t ||S )aJ  
        Send Laravel-style validation error response with detailed field errors.

        Args:
            errors: Dictionary of field names to lists of error messages
            message: General error message
            status_code: HTTP status code (default: 422)

        Returns:
            Flask Response object
        )r:   rZ   rH   )rZ   r:   r   r   r7   r7   r8   validation_error   s   zApiResponse.validation_errorpagination_infoc                 C   s   | |d}t |d|S )z8
        Send paginated response with metadata.
        )r   
paginationr   rH   )r   r\   r:   r   r3   r7   r7   r8   paginated_response   s   zApiResponse.paginated_responseresultsc                 C   sR   t dd | D }t| | }| t| ||dd}|dkr dnd}t|||S )z/
        Send bulk operation response.
        c                 s   s     | ]}| d drdV  qdS )r   F   N)r    ).0resultr7   r7   r8   	<genexpr>  s    z,ApiResponse.bulk_response.<locals>.<genexpr>)totalr   failed)r_   summaryr   r      )sumr$   r   r9   )r_   r:   r   success_countfailure_countr3   r   r7   r7   r8   bulk_response  s   	zApiResponse.bulk_responsec                 C   s,   | du r	t |S t | |}t |d|S )zn
        Send no content found response (HTTP 204).
        Equivalent to PHP's noDataFound() method.
        NrG   )r   rI   r<   r9   r?   r7   r7   r8   no_data_found  s   
zApiResponse.no_data_foundc                   C   s   t j  td dS )z=
        Clear response cache for memory management.
        zApiResponse cache clearedN)r   r#   clearr&   infor7   r7   r7   r8   clear_cache(  s   
zApiResponse.clear_cache)N)NNN)r   N)rY   rP   )NN)&__name__
__module____qualname____doc__r#   r%   staticmethodr   intr	   r   r"   r   r9   r
   r<   r@   rC   rF   rI   rJ   rK   rL   rM   rN   rO   rQ   rR   rS   rT   r(   rX   r   r[   r^   rk   rl   ro   r7   r7   r7   r8   r   
   sx    *<.
..."...2......**>:2r   r   r   r5   r   c                    s    fdd}|S )z:
    Decorator for automatic API response formatting.
    c                    s   t   fdd}|S )Nc               
      s   z! | i |}t |trt|dkr|W S tt|W S  ty` } z3tj	dd}t
jd j dt| dd |rMd jt|dd	}nd
di}t|W  Y d }~S d }~ww )N   r   FzUnhandled exception in r   Tr   zInternal server error)r:   functionr(   
debug_moder:   )r)   tupler$   r   r9   r<   	Exceptionr   r   r    r&   r(   rp   r"   rS   )argskwargsrb   er0   
error_data)funcr   r5   r   r7   r8   wrapper7  s,   
 z0api_response.<locals>.decorator.<locals>.wrapperr   )r   r   r   r5   r   )r   r8   	decorator6  s   zapi_response.<locals>.decoratorr7   )r   r5   r   r   r7   r   r8   api_response2  s   "r   Successr   r:   r   c                 C   s   t | |dS )+Legacy function for backward compatibility.r;   )r   r@   r;   r7   r7   r8   success_response\  s   r   An error occurredr   rW   c                 C   s   t | |S )r   )r   rX   )r:   rW   r7   r7   r8   error_response`     r   Resource not foundc                 C   s   t d| iS )r   r:   )r   rM   )r:   r7   r7   r8   not_found_responsed  s   r   rZ   c                 C   s   t d| S )r   zValidation errors)r   r[   )rZ   r7   r7   r8   validation_error_responseh  r   r   )r   NN)r   )r   r   )r   )flaskr   r   r   r   r   typingr   r   r	   r
   r   jsonloggingr   	functoolsr   	getLoggerrp   r&   r   ru   r"   r   r   r   r   r   r7   r7   r7   r8   <module>   s    
  (**"