# decorators.py
from functools import wraps

from django.conf import settings as s
from django.shortcuts import get_object_or_404

from epdb.logic import PackageManager

Package = s.GET_PACKAGE_MODEL()

# Map HTTP methods to required permissions
DEFAULT_METHOD_PERMISSIONS = {
    "GET": "read",
    "POST": "write",
    "DELETE": "write",
}


def package_permission_required(method_permissions=None):
    if method_permissions is None:
        method_permissions = DEFAULT_METHOD_PERMISSIONS

    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, package_uuid, *args, **kwargs):
            from epdb.views import _anonymous_or_real

            user = _anonymous_or_real(request)
            permission_required = method_permissions[request.method]

            # Check if the requested Package exists
            get_object_or_404(Package, uuid=package_uuid)

            if not PackageManager.has_package_permission(user, package_uuid, permission_required):
                from epdb.views import error

                return error(
                    request,
                    "Operation failed!",
                    f"Couldn't perform the desired operation as {user.username} does not have the required permissions!",
                    code=403,
                )

            return view_func(request, package_uuid, *args, **kwargs)

        return _wrapped_view

    return decorator
