# app/bot/utils/logging.py
from datetime import datetime, timezone

from flask import Flask

from app.extensions.db import db
from app.models import UserEvents
from telebot import logger

def log_user_event(chat_id: int, app: Flask, username: str, action: str) -> None:
    """
    Логирует действие пользователя в базу с использованием ORM.
    """
    try:
        with app.app_context():
            timestamp = datetime.now(timezone.utc)

            event = UserEvents(
                chat_id=chat_id,
                telegram_id=username,
                action=action,
                timestamp=timestamp
            )
            db.session.add(event)
            db.session.commit()

            formatted_time = timestamp.strftime('%Y-%m-%d %H:%M:%S')
            logger.info(f"User event logged: {chat_id} (@{username}) - {action} at {formatted_time}.")
    except Exception as e:
        logger.error(f"Error logging user event: {e}")
