"""
Custom permissions for Aimantis dashboard.

Provides structure-level access control to prevent
cross-tenant data leakage.
"""

from rest_framework import permissions

from structures.models import Structure, StructureUser


class HasStructureAccess(permissions.BasePermission):
    """
    Permission class to check if user has access to a specific structure.
    
    Supports:
    - Structure owners (user in owned_structures)
    - Structure users (via StructureUser relationship)
    - Superusers (full access)
    """
    
    def has_permission(self, request, view):
        """
        Check if the authenticated user has access to the requested structure.
        
        Args:
            request: HTTP request
            view: View being accessed
            
        Returns:
            True if user has access, False otherwise
        """
        # Must be authenticated (handled by IsAuthenticated)
        if not request.user or not request.user.is_authenticated:
            return False
        
        # Superusers have access to everything
        if request.user.is_superuser:
            return True
        
        # Get structure ID from query params
        structure_id = request.query_params.get("structure")
        
        # If no structure specified, allow (view will handle defaults)
        if not structure_id:
            return True
        
        try:
            structure_id = int(structure_id)
        except (ValueError, TypeError):
            return False
        
        # Check if user owns the structure
        if Structure.objects.filter(
            id=structure_id,
            user=request.user
        ).exists():
            return True
        
        # Check if user has access via StructureUser
        if StructureUser.objects.filter(
            structure_id=structure_id,
            user=request.user
        ).exists():
            return True
        
        # No access
        return False


class IsStaffOrReadOnly(permissions.BasePermission):
    """
    Custom permission to allow staff full access, others read-only.
    
    Prepares for future staff-specific dashboard features.
    """
    
    def has_permission(self, request, view):
        """
        Check permission based on user role and request method.
        
        Args:
            request: HTTP request
            view: View being accessed
            
        Returns:
            True if allowed, False otherwise
        """
        # Safe methods are always allowed
        if request.method in permissions.SAFE_METHODS:
            return True
        
        # Write methods require staff status
        return request.user and request.user.is_staff
