# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

from aws_lambda_powertools.event_handler import ApiGatewayResolver, Response
from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware


class BypassAuthMiddleware(BaseMiddlewareHandler):
    """
    Middleware to bypass authentication for specified paths.

    This middleware checks if the request path ends with any of the specified paths
    and adds a bypass_auth flag to the app context.
    """

    paths: list[str]

    def __init__(self, paths: list[str]) -> None:
        """Initialize the Bypass Auth middleware."""
        super().__init__()
        self.paths = paths

    def handler(
        self,
        app: ApiGatewayResolver,
        next_middleware: NextMiddleware,
    ) -> Response:
        """
        Process the API Gateway request and add a bypass_auth flag to the app context.

        NOTE: This handler is called by the AWS Lambda Powertools framework.

        Args:
            app: The API Gateway resolver instance
            next_middleware: The next middleware in the chain

        Returns:
            Response: The response from the next middleware
        """
        bypass_auth = any(app.current_event.path == path for path in self.paths)
        app.append_context(bypass_auth=bypass_auth)

        return next_middleware(app)
