# accounts/decorators.py
from functools import wraps
from django.contrib.auth.decorators import user_passes_test
from django.core.exceptions import PermissionDenied
from django.contrib import messages
from django.shortcuts import redirect


def role_required(allowed_roles):
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated and (request.user.role in allowed_roles or request.user.is_superuser):
                return view_func(request, *args, **kwargs)
            else:
                raise PermissionDenied('Access denied. Insufficient permissions.')
        return _wrapped_view
    return decorator


def perm_required(permission_field):
    """
    Decorator that checks RolePermission.<permission_field> for the current user's role.
    - Admins and superadmins always pass.
    - Redirects to permission_denied view if the permission is not granted.

    Usage:
        @perm_required('can_view_pnl')
        def my_view(request): ...
    """
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            user = request.user
            if not user.is_authenticated:
                return redirect('login')

            # Admins and superadmins always have full access
            if user.is_superuser or getattr(user, 'role', None) == 'admin':
                return view_func(request, *args, **kwargs)

            # Check RolePermission for this company+role
            company = getattr(request, 'company', None)
            if company:
                try:
                    from analytics.models import RolePermission
                    perm = RolePermission.get_for_role(company, user.role)
                    if getattr(perm, permission_field, False):
                        return view_func(request, *args, **kwargs)
                except Exception:
                    pass

            # Permission denied — redirect to friendly page
            return redirect('permission_denied')
        return _wrapped_view
    return decorator


def has_perm(request, permission_field):
    """
    Helper function to check a single RolePermission field for the current user.
    Returns True if the user is admin/superadmin or has the permission granted.
    Used in views and templates.
    """
    user = request.user
    if not user.is_authenticated:
        return False
    if user.is_superuser or getattr(user, 'role', None) == 'admin':
        return True
    company = getattr(request, 'company', None)
    if not company:
        return False
    try:
        from analytics.models import RolePermission
        perm = RolePermission.get_for_role(company, user.role)
        return getattr(perm, permission_field, False)
    except Exception:
        return False


# Specific role decorators
admin_required = role_required(['admin'])
manager_required = role_required(['admin', 'manager'])
cashier_required = role_required(['admin', 'manager', 'cashier'])