# Copyright (c) 2022 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
import functools
from typing import Mapping, Callable

from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent

from czc.api.web.cursor import Cursor
from czc.api.v2.pagination import unpack_cursor


def paginated(cursor_factory: Callable[[Mapping, Mapping], Cursor]):
    def decorator(handler):
        @functools.wraps(handler)
        def handler_wrapper(event, context, **kwargs):
            gateway_event = APIGatewayProxyEvent(event)
            cursor = unpack_cursor(gateway_event)
            unpacked_cursor = cursor_factory(
                cursor,
                gateway_event.query_string_parameters or {}
            )
            return handler(event, context, cursor=unpacked_cursor, **kwargs)

        return handler_wrapper

    return decorator
