
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from sqlalchemy.orm import Session
from app.db.models import OperationLog,User

from functools import wraps
from fastapi import Request



def log_operation(func):
    """自定义装饰器用于记录操作日志"""
    @wraps(func)
    async def wrapper(*args, **kwargs):
        if 'request' in kwargs and isinstance(kwargs['request'], Request):
            request: Request = kwargs['request']
            method = request.method
            url = str(request.url)
            client_ip = request.client.host
            headers = dict(request.headers)
            user_agent = headers.get("user-agent", "")

        if 'db' in kwargs and isinstance(kwargs['db'], Session):
            db = kwargs['db']
            if 'user' in kwargs and isinstance(kwargs['user'], User):
                user = kwargs['user']
                user_id = user.id
                tenant_id = user.tenantid
            else:
                user_id = None
                tenant_id = None
            
      
        try:
            response = await func(*args, **kwargs)
            if db:
                db_operation = OperationLog(tenantid =tenant_id,
                                            clientip =client_ip,
                                            useragent =user_agent,
                                            userid = user_id,
                                            operation = method,
                                            function = url,
                                            response = f"status_code:{response.status_code }"  )

                db.add(db_operation)
                db.commit()
        except Exception as e:
            raise e
        return response
    return wrapper

