import uuid
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpRequest


def get_tenant_id(request: HttpRequest):
    """
    Resolve the tenant_id from the request.
    Mirrors TenantMiddleware logic.
    """
    tenant_header = request.headers.get('X-Tenant-ID')
    if tenant_header:
        try:
            return uuid.UUID(tenant_header)
        except ValueError:
            return None
    elif hasattr(request, 'user') and request.user.is_authenticated:
        return getattr(request.user, 'current_organization_id', None)
    return None


class TenantMiddleware(MiddlewareMixin):
    """
    Middleware that attaches tenant_id to the request object.
    Resolves tenant_id from:
    1. Header 'X-Tenant-ID'
    2. Authenticated user's current_organization_id
    """
    def process_request(self, request):
        tenant_header = request.headers.get('X-Tenant-ID')
        if tenant_header:
            try:
                request.tenant_id = uuid.UUID(tenant_header)
            except ValueError:
                request.tenant_id = None
        elif hasattr(request, 'user') and request.user.is_authenticated:
            request.tenant_id = getattr(request.user, 'current_organization_id', None)
        else:
            request.tenant_id = None
