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

import konviva
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:
    new_image = event.detail['new_image']
    r = dyn.get_item(KeyPair(new_image['id'], 'konviva'))
    # Post-migration: uncomment the following line
    # r = dyn.get_item(KeyPair(new_image['id'], 'KONVIVA'))

    try:
        r = konviva.cancel_enrollment(r['enrollment_id'])
    except Exception as exc:
        logger.exception(exc)
        return False
    else:
        logger.info('Enrollment canceled', result=r)
        return True
