# 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

from czc.authorization import authorize_path

from czpowertools.constants import BYPASS_AUTH_CONTEXT_KEY


class OrganizationPathAuthorizerMiddleware(BaseMiddlewareHandler):
    """
    Middleware to authorize organization access based on URL path parameters.

    This middleware validates that the user has access to the organization specified
    in the URL path parameters using CloudZero's authorization system.
    """

    params: list[str]

    def __init__(self, params: list[str] | None = None) -> None:
        """
        Initialize the Organization Path Authorizer middleware.

        Args:
            params: List of path parameter names to authorize against.
                   Defaults to ['organizationId'].
        """
        super().__init__()
        self.params = params if params else ['organizationId']

    def handler(
        self,
        app: ApiGatewayResolver,
        next_middleware: NextMiddleware,
    ) -> Response:
        """
        Process the request and authorize path parameters.

        Uses CloudZero's authorize_path function to validate that the current user
        has access to the organization(s) specified in the URL path parameters.

        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

        Raises:
            AuthorizationError: If the user doesn't have access to the specified organization
        """
        if not app.context.get(BYPASS_AUTH_CONTEXT_KEY, False):
            authorize_path(app.current_event, self.params)
        return next_middleware(app)
