from functools import wraps
from quart import current_app, request
from taranis_base_bot.log import logger


def api_key_required(fn):
    @wraps(fn)
    async def wrapper(*args, **kwargs):
        api_key = (current_app.config.get("API_KEY") or "").strip()
        if not api_key:
            return await fn(*args, **kwargs)

        auth = request.headers.get("Authorization", "")
        if not auth.startswith("Bearer "):
            logger.warning("Missing Authorization Bearer")
            return {"error": "not authorized"}, 401
        if auth.removeprefix("Bearer ").strip() != api_key:
            logger.warning("Incorrect api key")
            return {"error": "not authorized"}, 401

        return await fn(*args, **kwargs)

    return wrapper
