from flask import abort, request
from app.decorators import content_negotiation
from app import db
from app.models import User
from . import bp


@bp.route('/users/<hashid:user_id>/confirmed', methods=['PUT'])
@content_negotiation(consumes='application/json', produces='application/json')
def update_user_role(user_id):
    confirmed = request.json
    if not isinstance(confirmed, bool):
        abort(400)
    user = User.query.get_or_404(user_id)
    user.confirmed = confirmed
    db.session.commit()
    response_data = {
        'message': (
            f'User "{user.username}" is now '
            f'{"confirmed" if confirmed else "unconfirmed"}'
        )
    }
    return response_data, 200