"""Block API routes that exceed the tenant subscription plan."""
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse

from app.core.config import settings
from app.core.database import SessionLocal
from app.services.plan_features import assert_api_path_allowed, feature_for_api_path


class PlanFeatureMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if not settings.license_enforcement:
            return await call_next(request)

        path = request.url.path
        if not path.startswith("/api/v1/"):
            return await call_next(request)

        if not feature_for_api_path(path):
            return await call_next(request)

        company_id = getattr(request.state, "company_id", None)
        if not company_id:
            return await call_next(request)

        db = SessionLocal()
        try:
            blocked = assert_api_path_allowed(db, company_id, path)
        finally:
            db.close()

        if blocked:
            feature_id = feature_for_api_path(path)
            return JSONResponse(
                status_code=403,
                content={
                    "success": False,
                    "error": "plan_feature_locked",
                    "feature": feature_id,
                    "message": blocked,
                },
            )

        return await call_next(request)
