from flask import request, current_app
from flask_login import current_user
from app.models.log import Log


def record_activity(action, target_type=None, target_id=None, description=None):
    """
    记录用户活动

    参数:
    - action: 操作类型，如 'login', 'logout', 'create', 'update', 'delete', 'borrow', 'return' 等
    - target_type: 操作对象类型，如 'book', 'user', 'borrow' 等
    - target_id: 操作对象ID
    - description: 操作详细描述
    """
    try:
        # 获取当前用户ID
        user_id = current_user.id if current_user.is_authenticated else None

        # 获取客户端IP地址
        ip_address = request.remote_addr
        if 'X-Forwarded-For' in request.headers:
            ip_address = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]

        # 记录日志
        Log.add_log(
            action=action,
            user_id=user_id,
            target_type=target_type,
            target_id=target_id,
            ip_address=ip_address,
            description=description
        )

        return True
    except Exception as e:
        # 记录错误，但不影响主要功能
        if current_app:
            current_app.logger.error(f"Error recording activity log: {str(e)}")
        return False
