from fastapi import Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware

from app.core.config import settings


class LandingModeMiddleware(BaseHTTPMiddleware):
    """
    Middleware that restricts API access when app is in landing mode.
    Only allows access to:
    - /health
    - /api/v1/contact
    - /api/v1/config/mode
    - / (root)
    - /docs, /redoc, /openapi.json (API documentation)
    """

    ALLOWED_PATHS = [
        "/",
        "/health",
        "/docs",
        "/redoc",
        "/openapi.json",
    ]

    ALLOWED_PREFIXES = [
        "/api/v1/contact",
        "/api/v1/config",
    ]

    async def dispatch(self, request: Request, call_next):
        # If not in landing mode, allow all requests
        if settings.app_mode != "landing":
            return await call_next(request)

        path = request.url.path

        # Check if path is in allowed list
        if path in self.ALLOWED_PATHS:
            return await call_next(request)

        # Check if path starts with allowed prefix
        for prefix in self.ALLOWED_PREFIXES:
            if path.startswith(prefix):
                return await call_next(request)

        # Block all other API requests in landing mode
        return JSONResponse(
            status_code=403,
            content={
                "detail": "API недоступен в режиме лендинга. Свяжитесь с нами через форму обратной связи.",
                "mode": "landing",
            },
        )
