"""
PREPOC ERP — Core Middleware
"""
import logging

from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger("prepoc")


class OrganizationMiddleware(MiddlewareMixin):
    """
    Injects request.organization based on:
    1. X-Organization-ID header (for multi-org users)
    2. The user's default organization
    Falls through silently for unauthenticated requests.
    """

    def process_request(self, request):
        request.organization = None

        if not request.user or not request.user.is_authenticated:
            return

        org_id = request.headers.get("X-Organization-Id")

        if org_id and org_id != "null":
            try:
                from apps.organizations.models import Organization
                from django.core.exceptions import ValidationError
                org = Organization.objects.get(id=org_id, is_active=True)
                # Verify user belongs to this org
                if request.user.organization_id == org.id or request.user.is_staff:
                    request.organization = org
                    return
            except (Organization.DoesNotExist, ValidationError):
                pass

        # Fallback: user's own organization
        if hasattr(request.user, "organization") and request.user.organization:
            request.organization = request.user.organization


class ActivityLogMiddleware(MiddlewareMixin):
    """
    Captures IP address and user agent for activity logging.
    Attaches them to the request for use by AuditMixin.
    """

    def process_request(self, request):
        x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
        if x_forwarded_for:
            request.client_ip = x_forwarded_for.split(",")[0].strip()
        else:
            request.client_ip = request.META.get("REMOTE_ADDR", "")
        request.user_agent = request.META.get("HTTP_USER_AGENT", "")
