"""Tenant header resolution middleware."""
from __future__ import annotations

from uuid import UUID

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

from shared.tenant import HEADER_TENANT_ID, STATE_TENANT_ID


class TenantHeaderMiddleware(BaseHTTPMiddleware):
    """Resolve tenant from X-Tenant-ID header only (microservice pattern)."""

    async def dispatch(self, request: Request, call_next) -> Response:
        setattr(request.state, STATE_TENANT_ID, None)
        raw = request.headers.get(HEADER_TENANT_ID)
        if raw:
            try:
                setattr(request.state, STATE_TENANT_ID, UUID(raw))
            except ValueError:
                pass
        return await call_next(request)
