# app/routes/users.py

from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user

# Импортируем функции сервисов напрямую
from app.services.users_service import get_users, get_user, toggle_block_user, delete_user, add_user, search_users
from app.services.users_event_service import log_user_action, get_user_events # Импортируем функции

users_bp = Blueprint('users', __name__, url_prefix='/users')

@users_bp.route('/', methods=['GET', 'POST'], strict_slashes=False)
@login_required
def manage_users_route():
    if request.method == 'GET':
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        return jsonify(get_users(page, per_page))
    elif request.method == 'POST':
        user_data = request.get_json()
        result, status_code = add_user(user_data, current_user)
        return jsonify(result), status_code
    return None


@users_bp.route('/<int:chat_id>', methods=['GET'])
@login_required
def get_user_route(chat_id):
    user = get_user(chat_id)
    if not user:
        return jsonify({'error': 'Пользователь не найден'}), 404
    return jsonify(user)

@users_bp.route('/<int:chat_id>/block', methods=['POST'])
@login_required
def block_user_route(chat_id):
    result, status_code = toggle_block_user(chat_id, current_user)
    return jsonify(result), status_code

@users_bp.route('/<int:chat_id>', methods=['DELETE'])
@login_required
def delete_user_route(chat_id):
    result, status_code = delete_user(chat_id, current_user)
    return jsonify(result), status_code

@users_bp.route('/<int:chat_id>/log', methods=['POST'])
@login_required
def log_user_action_route(chat_id):
    action = request.json.get('action')
    if action:
        result, status_code = log_user_action(chat_id, action) # Вызываем функцию напрямую
        return jsonify(result), status_code
    else:
        return jsonify({'error': 'Не указано действие'}), 400

@users_bp.route('/search', methods=['GET'])
@login_required
def search_users_route():
    telegram_id = request.args.get('telegram_id')
    email = request.args.get('email')
    users = search_users(telegram_id, email)
    return jsonify(users)

@users_bp.route('/<int:chat_id>/user_events', methods=['GET'])
@login_required
def handle_user_events_route(chat_id):
    result, status_code = get_user_events(chat_id) # Вызываем функцию напрямую
    return jsonify(result), status_code