from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from models.user import Users

admin_user_bp = Blueprint("admin_user", __name__, url_prefix="/admin/users")

# Get all users with role "user"
@admin_user_bp.route("/", methods=["GET"])
@jwt_required()
def get_all_users():
    users_model = Users()
    users = users_model.get_all_users_with_role("user")
    return jsonify(users), 200

# Get all users with role "user"
@admin_user_bp.route("/company_users", methods=["GET"])
@jwt_required()
def get_all_company_users():
    users_model = Users()
    users = users_model.get_all_users_with_role("company_user")
    return jsonify(users), 200

# Get a single user by ID
@admin_user_bp.route("/<int:user_id>", methods=["GET"])
@jwt_required()
def get_user(user_id):
    users_model = Users()
    user = users_model.get_user_by_id(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404
    return jsonify(user), 200

# Update a user
@admin_user_bp.route("/update", methods=["POST"])
@jwt_required()
def update_user():
    if not request.is_json:
        print("Content-Type received:", request.content_type)
        return jsonify({"error": "Invalid content type, must be application/json"}), 415

    data = request.get_json()
    if not data.get("user_id"):
        return jsonify({"error": "Missing user_id"}), 400

    users_model = Users()
    users_model.update_user(data)

    return jsonify({"message": "User updated successfully."}), 200

# Deactivate
@admin_user_bp.route("/deactivate", methods=["POST"])
@jwt_required()
def deactivate_user():
    if not request.is_json:
        print("Content-Type received:", request.content_type)
        return jsonify({"error": "Invalid content type, must be application/json"}), 415

    data = request.get_json()
    user_id = data.get("user_id")
    if not user_id:
        return jsonify({"error": "Missing user_id"}), 400

    users_model = Users()
    users_model.deactivate_user(user_id)

    return jsonify({"message": "User updated successfully."}), 200