import base64
from flask import request, jsonify
from functools import wraps
from modules.users.service import authenticate_user


def rest_auth_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        auth = request.headers.get("Authorization")

        if not auth or not auth.startswith("Basic "):
            return jsonify({"error": "authorization required"}), 401

        try:
            decoded = base64.b64decode(auth.split(" ")[1]).decode()
            username, password = decoded.split(":", 1)
        except Exception:
            return jsonify({"error": "invalid authorization header"}), 401

        user = authenticate_user(username, password)
        if not user:
            return jsonify({"error": "invalid credentials"}), 401

        # opcional: passar user adiante
        request.rest_user = user

        return f(*args, **kwargs)

    return wrapper