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 now
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair

from boto3clients import dynamodb_client
from config import (
    ENROLLMENT_TABLE,
)

logger = Logger(__name__)
dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)


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

    try:
        with dyn.transact_writer() as transact:
            transact.update(
                key=KeyPair(
                    pk=old_image['id'],
                    sk='0',
                ),
                update_expr='SET access_expired = :true, updated_at = :now',
                expr_attr_values={
                    ':true': True,
                    ':now': now_,
                },
            )
            transact.put(
                item={
                    'id': old_image['id'],
                    'sk': 'SCHEDULE#SET_ACCESS_EXPIRED#EXECUTED',
                    'created_at': now_,
                },
            )
    except Exception as exc:
        logger.exception(exc)

        dyn.put_item(
            item={
                'id': old_image['id'],
                'sk': 'SCHEDULE#SET_ACCESS_EXPIRED#FAILED',
                'reason': str(exc),
                'created_at': now_,
            },
        )

        return False
    else:
        return True
