import warnings
from typing import cast

from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware

from starlette_proxy_router.exceptions import ProxyAuthenficationError
from starlette_proxy_router.parser import EndpointArgs


def check_auth_midlleware(
    middlewares: list[Middleware], endpoints_args: list[EndpointArgs]
) -> None:
    auth_midlleware = any(
        issubclass(cast(type, middleware.cls), AuthenticationMiddleware)
        for middleware in middlewares
    )
    auth_endpoints = any(args.is_auth for args in endpoints_args)

    if auth_midlleware and not auth_endpoints:
        warnings.warn(
            "Existing AuthenticationMiddleware is not used in proxy routes",
            DeprecationWarning,
            stacklevel=2,
        )
    elif not auth_midlleware and auth_endpoints:
        raise ProxyAuthenficationError(
            "The application does not have AuthenticationMiddleware implemented or added"
        )
