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

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


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    """Remove slots if the tenant has a `metadata#billing_policy` and
    the total is greater than zero."""
    new_image = event.detail['new_image']
    data = order_layer.get_item(KeyPair(new_image['id'], '0'))
    tenant_id = data['tenant_id']

    policy = user_layer.collection.get_item(
        KeyPair(pk=tenant_id, sk='metadata#billing_policy'),
        raise_on_error=False,
        default=False,
    )

    # Skip if billing policy is missing or order is less than or equal to zero
    if not policy or data['total'] <= 0:
        logger.info('Missing billing policy.')
        return False

    logger.info(f'Billing policy from Tenant ID "{tenant_id}" found', policy=policy)

    result = enrollment_layer.collection.query(
        KeyPair(
            ComposeKey(tenant_id, prefix='vacancies'),
            new_image['id'],
        )
    )

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

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

        logger.info('Deleted all slots')

    return True
