"""
User management routes
"""
import os
from flask import Blueprint, request, jsonify, current_app, make_response
from werkzeug.utils import secure_filename
from utils import require_api_key, add_keep_alive, allowed_file, format_api_response, create_error_response, format_validation_error, format_unauthorized_error
from auth.jwt_manager import require_auth, require_user_access
from flask import g
from database import get_cached_connection
from profile_ import profile_fnc
from home import home_fnc


user_bp = Blueprint('user', __name__)


@user_bp.route('/update-profile', methods=['POST'])
@require_api_key
@require_auth
@require_user_access
def update_profile():
    conn = get_cached_connection()
    cursor = conn.cursor()

    user_id = getattr(g, 'current_user_id', None) or request.values.get('user_id')
    name = request.form.get('name')
    email = request.form.get('email')
    phone = request.form.get('phone')
    new_password = request.form.get('password')  # New password (optional)
    old_password = request.form.get('old_password')  # Old password (optional)

    file = request.files.get('profile_image')  # Optional profile image upload

    # Ensure that user_id is provided
    if not user_id:
        return format_validation_error({"user_id": "required"}, "User ID is required")

    # Construct the SQL query to update the user's profile
    update_fields = []
    update_values = []

    if name:
        update_fields.append("fullname = %s")
        update_values.append(name)

    if email:
        update_fields.append("email = %s")
        update_values.append(email)

    if phone:
        update_fields.append("contactno = %s")
        update_values.append(phone)

    # Handle password update
    if new_password:
        if not old_password:
            return format_validation_error(
                {"old_password": "required for password update"},
                "Old password required for password update"
            )

        # Check if the old password matches
        cursor.execute("SELECT password FROM `user` WHERE id = %s", (user_id,))
        result = cursor.fetchone()
        if not result or result[0] != old_password:
            return format_unauthorized_error("Old password does not match")

        # If old password matches, allow password update
        update_fields.append("password = %s")
        update_values.append(new_password)

    # Handle the profile image upload
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        update_fields.append("profile_img_url = %s")
        update_values.append(
            "https://clc.ashlya.com/study/api/profile_images/" + filename)

    # If there are no fields to update, return an error
    if not update_fields:
        return format_validation_error({}, "No fields to update")

    # Add the user_id to update values and create the final SQL query
    update_values.append(user_id)
    update_query = "UPDATE `user` SET {} WHERE `id` = %s".format(', '.join(update_fields))

    try:
        # Execute the update query
        cursor.execute(update_query, tuple(update_values))
        conn.commit()

        # Close cursor and connection
        cursor.close()
    except Exception as e:
        print("Error updating user profile: {}".format(e))
        return create_error_response(
            "Failed to update profile",
            status_code=500,
            error_code="PROFILE_UPDATE_ERROR",
            error_details=str(e)
        )
    finally:
        # Make sure the connection is properly closed
        if conn and hasattr(conn, 'close'):
            conn.close()

    return jsonify(format_api_response(
        data={"user_id": user_id},
        message="Profile updated successfully",
        include_legacy_fields={"response": "success", "message": "Profile updated successfully"}
    )), 200


@user_bp.route('/profile', methods=['POST', 'GET'])
@require_auth
@require_user_access
def profi():
    response = make_response(profile_fnc(request))
    return add_keep_alive(response)


@user_bp.route('/home', methods=['POST', 'GET'])
@require_api_key
@require_auth
@require_user_access
def home():
    response = make_response(home_fnc(request))
    return add_keep_alive(response)