from datetime import timedelta

from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.data_classes import (
    EventBridgeEvent,
    event_source,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dateutils import fromisoformat, now, ttl
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
)

from boto3clients import dynamodb_client
from config import ORDER_TABLE

logger = Logger(__name__)
order_layer = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    due_date = fromisoformat(new_image['due_date'])
    now_ = now()

    if not due_date:
        return False

    return order_layer.put_item(
        item={
            'id': new_image['id'],
            'sk': 'schedules#set_as_expired',
            'ttl': ttl(start_dt=due_date + timedelta(hours=24)),
            'created_at': now_,
        }
    )
