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

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']
    user_id = new_image['user_id']
    class_id = new_image['class_id']
    now_ = now()

    try:
        enrollment_id = konviva.enroll(
            user_id,
            class_id,
        )
    except konviva.KonvivaError as err:
        logger.exception(err)
        return False

    with dyn.transact_writer() as transact:
        transact.update(
            key=KeyPair(new_image['id'], 'konviva'),
            # Post-migration: uncomment the following line
            # key=KeyPair(new_image['id'], 'KONVIVA'),
            update_expr='SET enrollment_id = :enrollment_id',
            cond_expr='attribute_exists(sk)',
            expr_attr_values={
                ':enrollment_id': enrollment_id,
            },
        )
        # To relate with the enrollment
        transact.put(
            item={
                'id': 'konviva',
                # Post-migration: uncomment the following line
                # 'id': 'KONVIVA',
                'sk': str(enrollment_id),
                'enrollment_id': new_image['id'],
                'created_at': now_,
            }
        )

        return True
