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

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:
    new_image = event.detail['new_image']
    order_id = new_image['id']
    data = order_layer.collection.get_items(
        TransactKey(order_id)
        + SortKey('0')
        + KeyPair(
            pk=order_id,
            sk=SortKey(
                'metadata#tenant',
                path_spec='tenant_id',
                remove_prefix='metadata#',
            ),
            rename_key='tenant_id',
        )
    )
    total = data['total']
    tenant_id = data['tenant_id'].removeprefix('ORG#')

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

    if not policy or total <= 0:
        return False

    result = enrollment_layer.collection.query(
        KeyPair(
            ComposeKey(tenant_id, prefix='vacancies'),
            order_id,
        )
    )
    with enrollment_layer.batch_writer() as batch:
        for pair in result['items']:
            batch.delete_item(
                Key={
                    'id': {'S': f'vacancies#{pair["id"]}'},
                    'sk': {'S': pair['sk']},
                }
            )

    return True
