from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from .models import Organization

class OrganizationMiddleware(MiddlewareMixin):
    """
    Middleware to detect the current organization from the request.
    Priority:
    1. Header 'X-Organization-ID' (for API/Admin)
    2. User profile (if authenticated)
    """

    def process_request(self, request):
        request.organization = None
        request.organization_header_provided = False
        request.organization_header_valid = True

        # 1. Check header (support both legacy and alias header names)
        raw_org_value = (
            request.headers.get('X-Organization-ID')
            or request.headers.get('X-Organization')
        )
        if raw_org_value:
            request.organization_header_provided = True
            org_value = str(raw_org_value).strip()
            try:
                if org_value.isdigit():
                    request.organization = Organization.objects.get(organization_id=int(org_value))
                else:
                    request.organization = Organization.objects.get(code=org_value)
                return
            except (Organization.DoesNotExist, ValueError, TypeError):
                request.organization_header_valid = False
                return

        # 2. Check user profile
        if request.user.is_authenticated:
            try:
                if hasattr(request.user, 'profile') and request.user.profile.organization:
                    request.organization = request.user.profile.organization
            except Exception:
                pass
