# -*- coding: utf-8 -*-
"""
audit.py — 操作日志查询路由
"""

from flask import Blueprint, request, jsonify, g
from decorators import login_required
from services.audit_service import get_logs, get_users_with_logs, MODULE_ACTIONS, ACTION_LABELS

bp = Blueprint('audit', __name__, url_prefix='/api/audit')


@bp.route('/logs', methods=['GET'])
@login_required
def list_logs():
    """分页查询操作日志"""
    module = request.args.get('module', 'troubleshoot')
    page = request.args.get('page', 1, type=int)
    page_size = request.args.get('pageSize', 20, type=int)
    start_time = request.args.get('startTime')
    end_time = request.args.get('endTime')
    action_type = request.args.get('actionType')
    user = request.args.get('user')

    # 参数校验
    if module not in ('troubleshoot', 'monitor', 'manage'):
        return jsonify({
            'success': False,
            'error': {'code': 400, 'message': '无效的模块参数'}
        }), 400

    if page < 1:
        page = 1
    if page_size < 1 or page_size > 100:
        page_size = 20

    result = get_logs(
        module=module,
        page=page,
        page_size=page_size,
        start_time=start_time,
        end_time=end_time,
        action_type=action_type,
        user=user
    )

    return jsonify({
        'success': True,
        'data': result
    })


@bp.route('/users', methods=['GET'])
@login_required
def list_users():
    """获取有操作记录的用户列表"""
    module = request.args.get('module')
    users = get_users_with_logs(module=module)
    return jsonify({
        'success': True,
        'data': users
    })


@bp.route('/actions/<module>', methods=['GET'])
@login_required
def list_actions(module):
    """获取模块的操作类型列表"""
    if module not in MODULE_ACTIONS:
        return jsonify({
            'success': False,
            'error': {'code': 404, 'message': '模块不存在'}
        }), 404

    actions = MODULE_ACTIONS[module]
    action_list = [
        {'value': action, 'label': ACTION_LABELS.get(action, action)}
        for action in actions
    ]
    return jsonify({
        'success': True,
        'data': action_list
    })
