from flask import Blueprint, request, jsonify
from uuid import UUID
from db.model import db, User, Course, Enrollment

chat = Blueprint('chat', __name__)

@chat.route('/course/<uuid:course_id>/users', methods=['POST'])
def get_users_assigned_to_course(course_id: UUID):
    """
    Fetch all users assigned to a specific course.
    :param course_id: ID of the course to fetch users for (UUID).
    :return: JSON response with users assigned to the course.
    """
    try:
        # Query the course to ensure it exists
        course = Course.query.get(course_id)
        if not course:
            return jsonify({"error": "Course not found."}), 404

        # Get the list of users assigned to the course
        users = User.query.filter(User.enrollments.any(course_id=course_id)).all()

        # Prepare the response data
        user_data = [
            {
                "id": user.id,
                "email": user.email,
                "username": user.username,
                "firstName": user.firstName,
                "lastName": user.lastName,
            }
            for user in users
        ]

        return jsonify({"course": course.name, "users": user_data}), 200
    except Exception as e:
        return jsonify({"error": f"An error occurred: {str(e)}"}), 500


@chat.route('/course/<uuid:course_id>/chat', methods=['POST'])
def join_chat(course_id: UUID):
    """
    Allow users to join the chat only if they are enrolled in the course.
    :param course_id: ID of the course (UUID).
    :return: JSON response indicating whether the user can join or not.
    """
    try:
        # Get the user from the request (assume user_id is passed in the request body)
        user_id = request.json.get('user_id')
        if not user_id:
            return jsonify({"error": "User ID is required."}), 400

        # Query the user and ensure they exist
        user = User.query.get(user_id)
        if not user:
            return jsonify({"error": "User not found."}), 404

        # Check if the user is enrolled in the course
        enrollment = Enrollment.query.filter_by(userID=user_id, courseID=course_id).first()
        if not enrollment:
            return jsonify({"error": "User is not enrolled in this course."}), 403

        # If enrolled, allow the user to join the chat
        return jsonify({"message": f"User {user.username} is enrolled in the course and can join the chat."}), 200
    except Exception as e:
        return jsonify({"error": f"An error occurred: {str(e)}"}), 500
