from flask import Flask, request, jsonify
from flask_cors import CORS
from user_management import register_user, authenticate_user, delete_user, reactivate_user, \
deactivate_user, retrieve_security_question, verify_security_answer, reset_password, update_user, retrieve_email

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes
    
@app.route('/register', methods=['POST'])
def register_user_route():
    data = request.json
    username = data.get('username')
    full_name = data.get('fullName')
    email = data.get('email')
    password = data.get('password')
    security_question = data.get('securityQuestion')
    security_answer = data.get('securityAnswer')

    if not all([username, full_name, email, password, security_question, security_answer]):
        return jsonify({"success": False, "message": "All fields are required."}), 400

    register_result = register_user(full_name=full_name, email=email, password=password, username=username, security_question=security_question, security_answer=security_answer)

    if register_result.get("success"):
        return jsonify({"success": True, "message": "User registered successfully."})
    else:
        return jsonify({"success": False,
                        "message": register_result.get("message")}), 400
    
@app.route('/login', methods=['POST'])
def login_user_route():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    login_result = authenticate_user(username=username, password=password)
    if login_result.get("success"):
        return jsonify({"success": True, "message": "User logged in successfully."})
    else:
        return jsonify({"success": False,
                        "message": "Invalid username or password"}), 400

@app.route('/delete_user', methods=['POST'])
def delete_user_route():
    data = request.json
    username = data.get('username')

    delete_result = delete_user(username)
    return jsonify({"result": delete_result})

@app.route('/reactivate_user', methods=['POST'])
def reactivate_user_route():
    data = request.json
    username = data.get('username')

    reactivate_result = reactivate_user(username)
    return jsonify({"result": reactivate_result})

@app.route('/deactivate_user', methods=['POST'])
def deactivate_user_route():
    data = request.json
    username = data.get('username')

    deactivate_result = deactivate_user(username)
    return jsonify({"result": deactivate_result})

@app.route('/retrieve_security_question', methods=['POST'])
def retrieve_security_question_route():
    data = request.json
    username = data.get('username')
    user_response = retrieve_security_question(username= username)
    if user_response.get("success"):
        return jsonify({"success": True, "securityQuestion": user_response.get("securityQuestion")})
    else:
        return jsonify({"success": False,
                        "message": "User does not exist."}), 400
    
@app.route('/retrieve_email', methods=['POST'])
def retrieve_email_route():
    data = request.json
    username = data.get('username')
    user_response = retrieve_email(username= username)
    if user_response.get("success"):
        return jsonify({"success": True, "email": user_response.get("email")})
    else:
        return jsonify({"success": False,
                        "message": "User does not exist."}), 400

@app.route('/verify_security_answer', methods=['POST'])
def verify_security_answer_route():
    data = request.json
    securityAnswer = data.get('securityAnswer')
    username = data.get('username')

    verification = verify_security_answer(username, securityAnswer)
    if verification.get("success"):
        return jsonify({"success": True, "securityQuestion": verification.get("securityQuestion")})
    else:
        return jsonify({"success": False,
                        "message": verification.get("message")}), 400
    
@app.route('/reset_password', methods=['POST'])
def reset_password_route():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    confirmpassword = data.get('confirmPassword')

    password_reset = reset_password(username = username, new_password=password, confirm_new_password=confirmpassword)
    if password_reset.get("success"):
        return jsonify({"success": True, "securityQuestion": password_reset.get("message")})
    else:
        return jsonify({"success": False,
                        "message": password_reset.get("message")}), 400
    
@app.route('/update_user', methods=['POST'])
def update_user_route():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    if not any([username, password]):
        return jsonify({"success": False, "message": "No updates have been made."}), 400

    update_result = update_user(username=username, password=password)

    if update_result.get("success"):
        return jsonify({"success": True, "message": "User registered successfully."})
    else:
        return jsonify({"success": False,
                        "message": update_result.get("message")}), 400
    

@app.route('/update_user_settings', methods=['POST'])
def update_user_settings_route():
    data = request.json
    updates = {}

    # Collect only the fields that have been updated
    old_username = data.get('old_username')

    if data.get('username'):
        updates['username'] = data.get('username')
    if data.get('email'):
        updates['email'] = data.get('email')
    if data.get('password'):
        updates['password'] = data.get('password')
    if data.get('confirmpassword'):
        updates['confirmpassword'] = data.get('confirmpassword')
    if data.get('securityQuestion'):
        updates['securityquestion'] = data.get('securityQuestion')
    if data.get('securityAnswer'):
        updates['securityanswer'] = data.get('securityAnswer')

    # Ensure at least one field is provided for update
    if not updates:
        return jsonify({"success": False, "message": "No updates have been made."}), 400

    # Call the update_user function, passing only the necessary fields
    update_result = update_user(cur_username=old_username, **updates)

    if update_result.get("success"):
        return jsonify({"success": True, "message": "User settings updated successfully."})
    else:
        return jsonify({"success": False, "message": update_result.get("message")}), 400
    
if __name__ == '__main__':
    app.run(debug=True, port=5001)