from flask import Blueprint, request, jsonify, current_app
from models.user import User
from tinydb import Query
from db.db import users_db
import jwt

user_api = Blueprint('user_api', __name__)
UserQuery = Query()

def get_current_user():
    token = request.cookies.get('token')
    if not token:
        return None
    try:
        payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
        email = payload.get('email')
        user_dict = users_db.get(UserQuery.email == email)
        return User.from_dict(user_dict) if user_dict else None
    except Exception:
        return None

@user_api.route('/user/profile', methods=['GET'])
def get_profile():
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Unauthorized'}), 401
    return jsonify({
        'first_name': user.first_name,
        'last_name': user.last_name,
        'email': user.email,
        'image_id': user.image_id
    }), 200

@user_api.route('/user/image', methods=['PUT'])
def update_image():
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Unauthorized'}), 401
    data = request.get_json()
    image_id = data.get('image_id')
    if not image_id:
        return jsonify({'error': 'Missing image_id'}), 400
    user.image_id = image_id
    users_db.update(user.to_dict(), UserQuery.email == user.email)
    return jsonify({'message': 'Image updated', 'image_id': image_id}), 200
