"""
Role-based rate limiting middleware.
"""
from slowapi import Limiter
from slowapi.util import get_remote_address
from typing import Callable
from fastapi import Request
from ...shared.config.settings import settings
from ...shared.config.logging_config import get_logger

logger = get_logger(__name__)

def get_rate_limit_key(request: Request) -> str:
    """Get rate limit key based on user role if authenticated, otherwise IP."""
    # Try to get user from request state (set by auth middleware)
    if hasattr(request.state, 'user') and request.state.user:
        user = request.state.user
        # Get user role
        role = getattr(user, 'role', None)
        if role:
            role_name = getattr(role, 'name', None)
            if role_name:
                # Return role-based key
                return f"rate_limit:{role_name}:{user.id}"
    
    # Fall back to IP-based limiting
    return get_remote_address(request)

def get_rate_limit_for_role(role_name: str) -> str:
    """Get rate limit string for a specific role."""
    limits = {
        'admin': settings.RATE_LIMIT_ADMIN_PER_MINUTE,
        'staff': settings.RATE_LIMIT_STAFF_PER_MINUTE,
        'accountant': settings.RATE_LIMIT_ACCOUNTANT_PER_MINUTE,
        'customer': settings.RATE_LIMIT_CUSTOMER_PER_MINUTE,
    }
    
    limit = limits.get(role_name, settings.RATE_LIMIT_PER_MINUTE)
    return f"{limit}/minute"

def create_role_based_limiter() -> Limiter:
    """Create a role-based rate limiter."""
    return Limiter(
        key_func=get_rate_limit_key,
        default_limits=[f'{settings.RATE_LIMIT_PER_MINUTE}/minute']
    )

