# app/api/v1/auth.py
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt
from app.services.auth_service import AuthService

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        if not data:
            return jsonify({'msg': '无效的请求数据'}), 400

        if not data.get('username') or not data.get('password'):
            return jsonify({'msg': '请输入用户名和密码'}), 400

        result = AuthService.login(data)

        response_data = {
            'msg': '登录成功',
            'access_token': result.get('access_token'),
            'user': result.get('user')
        }
        return jsonify(response_data), 200

    except ValueError as ve:
        return jsonify({'msg': str(ve)}), 401
    except Exception as e:
        current_app.logger.error(f"Login Failed Error: {str(e)}")
        return jsonify({'msg': f'服务器内部错误: {str(e)}'}), 500


@auth_bp.route('/user/create', methods=['POST'])
@jwt_required()
def create_user():
    try:
        data = request.get_json()
        claims = get_jwt()
        operator_role = claims.get('role')

        result = AuthService.create_user(data, operator_role)
        return jsonify({'msg': '用户创建成功', 'data': result}), 201

    except Exception as e:
        current_app.logger.error(f"User Create Failed: {str(e)}")
        return jsonify({'msg': str(e)}), 400


# [新增] 更新用户
@auth_bp.route('/user/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    try:
        data = request.get_json()
        claims = get_jwt()
        operator_role = claims.get('role')

        result = AuthService.update_user(user_id, data, operator_role)
        return jsonify({'msg': '用户更新成功', 'data': result}), 200

    except Exception as e:
        current_app.logger.error(f"User Update Failed: {str(e)}")
        return jsonify({'msg': str(e)}), 400


@auth_bp.route('/users', methods=['GET'])
@jwt_required()
def get_users():
    try:
        users = AuthService.get_all_users()
        return jsonify({'msg': '获取成功', 'data': users}), 200
    except Exception as e:
        current_app.logger.error(f"Get Users Failed: {str(e)}")
        return jsonify({'msg': '获取用户列表失败'}), 500


@auth_bp.route('/user/<int:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    try:
        claims = get_jwt()
        operator_role = claims.get('role')

        AuthService.delete_user(user_id, operator_role)
        return jsonify({'msg': '删除成功'}), 200
    except Exception as e:
        current_app.logger.error(f"Delete User Failed: {str(e)}")
        return jsonify({'msg': str(e)}), 400