# inventory-backend/app/api/v1/permission.py
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required
from app.services.permission_service import PermissionService
from app.utils.decorators import audit_log

permission_bp = Blueprint('permission', __name__)


@permission_bp.route('/tree', methods=['GET'])
@jwt_required()
def get_tree():
    """获取权限树"""
    try:
        data = PermissionService.get_permission_tree()
        return jsonify({'code': 200, 'msg': '获取成功', 'data': data}), 200
    except Exception as e:
        # 打印详细错误到控制台，方便调试
        current_app.logger.error(f"Get Tree Failed: {str(e)}")
        # 返回 500 时带上错误信息
        return jsonify({'code': 500, 'msg': f'服务器内部错误: {str(e)}'}), 500


@permission_bp.route('/role/<string:role_code>', methods=['GET'])
@jwt_required()
def get_role_perms(role_code):
    """获取某个角色的权限列表"""
    try:
        data = PermissionService.get_role_permissions(role_code)
        return jsonify({'code': 200, 'msg': '获取成功', 'data': data}), 200
    except Exception as e:
        current_app.logger.error(f"Get Role Perms Failed: {str(e)}")
        return jsonify({'code': 500, 'msg': str(e)}), 500


@permission_bp.route('/assign', methods=['POST'])
@jwt_required()
@audit_log(
    module='权限管理',
    action='分配',
    get_target_name_fn=lambda: request.get_json().get('role_code') if request.get_json() else None
)
def assign_perms():
    """保存权限分配"""
    try:
        data = request.get_json()
        role_code = data.get('role_code')
        permissions = data.get('permissions', [])  # list of codes

        PermissionService.assign_permissions(role_code, permissions)
        return jsonify({'code': 200, 'msg': '保存成功'}), 200
    except Exception as e:
        current_app.logger.error(f"Assign Perms Failed: {str(e)}")
        return jsonify({'code': 500, 'msg': str(e)}), 500