"""
inventory/permissions.py
─────────────────────────
Role-based permissions for the inventory app.

Roles (implemented via Django groups):
  inventory_managers  – full CRUD on stock and sales
  finance_managers    – full access to payouts, expenses, reports
  super_admins        – is_superuser

All roles require is_staff=True.
"""

from rest_framework.permissions import BasePermission, SAFE_METHODS


class IsSuperAdmin(BasePermission):
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_authenticated and request.user.is_superuser)


class IsInventoryManager(BasePermission):
    """Staff user in the 'inventory_managers' group, or a superuser."""
    def has_permission(self, request, view):
        if not (request.user and request.user.is_authenticated and request.user.is_staff):
            return False
        if request.user.is_superuser:
            return True
        return request.user.groups.filter(name="inventory_managers").exists()


class IsFinanceManager(BasePermission):
    """Staff user in the 'finance_managers' group, or a superuser."""
    def has_permission(self, request, view):
        if not (request.user and request.user.is_authenticated and request.user.is_staff):
            return False
        if request.user.is_superuser:
            return True
        return request.user.groups.filter(name="finance_managers").exists()


class IsInventoryOrFinanceManager(BasePermission):
    """Either inventory_managers OR finance_managers (or superuser)."""
    def has_permission(self, request, view):
        if not (request.user and request.user.is_authenticated and request.user.is_staff):
            return False
        if request.user.is_superuser:
            return True
        return request.user.groups.filter(
            name__in=["inventory_managers", "finance_managers"]
        ).exists()


class IsInventoryManagerOrReadOnlyForStaff(BasePermission):
    """
    SAFE_METHODS allowed to any authenticated staff.
    Writes require inventory_managers group or superuser.
    """
    def has_permission(self, request, view):
        if not (request.user and request.user.is_authenticated and request.user.is_staff):
            return False
        if request.method in SAFE_METHODS:
            return True
        if request.user.is_superuser:
            return True
        return request.user.groups.filter(name="inventory_managers").exists()
