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,
)

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)


@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']
    org_id = new_image['tenant_id']
    # Post-migration (orders): Uncomment the following line
    # org_id = new_image['org_id']

    r = enrollment_layer.collection.query(
        KeyPair(
            # Post-migration: Uncomment the following line
            # f'SLOT#ORG#{org_id}',
            pk=f'vacancies#{org_id}',
            sk=order_id,
        ),
        limit=100,
    )

    logger.info(
        'Slots found',
        total_items=len(r['items']),
        slots=r['items'],
    )

    with enrollment_layer.batch_writer() as batch:
        for pair in r['items']:
            batch.delete_item(
                Key={
                    'id': {'S': pair['id']},
                    'sk': {'S': pair['sk']},
                }
            )

        logger.info('Slots deleted')

    return True
