"""ثبت فعالیت کاربران در جدول activity_log — پورت‌شده از core/logger.py دسکتاپ."""
from app.extensions import db
from app.models.activity_log import ActivityLog


def log_action(user, action_type: str, entity_type: str = None, entity_id=None, details: dict = None):
    entry = ActivityLog(
        user_id=user.id if user else None,
        username=user.username if user else "system",
        action_type=action_type,
        entity_type=entity_type,
        entity_id=entity_id,
        details=details,
    )
    db.session.add(entry)
    db.session.commit()


def list_logs(limit=500, user_id=None, action_type=None):
    query = ActivityLog.query
    if user_id:
        query = query.filter(ActivityLog.user_id == user_id)
    if action_type:
        query = query.filter(ActivityLog.action_type == action_type)
    return query.order_by(ActivityLog.id.desc()).limit(limit).all()
