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 (
    ComposeKey,
    DynamoDBPersistenceLayer,
    KeyPair,
)

from boto3clients import dynamodb_client
from config import ENROLLMENT_TABLE, ORDER_TABLE

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


class TenantDoesNotExistError(Exception):
    def __init__(self, *args):
        super().__init__('Tenant does not exist')


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    order_id = new_image['id']
    tenant_id = new_image['tenant']

    result = enrollment_layer.collection.query(
        KeyPair(
            # Post-migration: Uncomment the following line
            # ComposeKey(tenant_id, prefix='slots#org'),
            ComposeKey(tenant_id, prefix='vacancies'),
            order_id,
        )
    )

    logger.info('Slots found', slots=result['items'])

    with enrollment_layer.batch_writer() as batch:
        for pair in result['items']:
            batch.delete_item(
                Key={
                    # Post-migration: Rename `vacancies` to `slots#org`
                    'id': {'S': ComposeKey(pair['id'], prefix='vacancies')},
                    'sk': {'S': pair['sk']},
                }
            )

        logger.info('Slots deleted')

    return True
