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

from boto3clients import dynamodb_client
from config import (
    ENROLLMENT_TABLE,
    USER_TABLE,
)

logger = Logger(__name__)
user_layer = DynamoDBPersistenceLayer(USER_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']
    now_ = now()
    terms = user_layer.get_item(
        # Post-migration (users): uncomment the following line
        # KeyPair(new_image['org_id'], 'METADATA#SUBSCRIPTION'),
        KeyPair(new_image['org_id'], 'metadata#billing_policy'),
    )

    if not terms:
        return False

    try:
        with enrollment_layer.transact_writer() as transact:
            transact.update(
                key=KeyPair(new_image['id'], '0'),
                update_expr='SET subscription_covered = :subscription_covered, \
                                 updated_at = :now',
                expr_attr_values={
                    ':subscription_covered': True,
                    ':now': now_,
                },
                cond_expr='attribute_exists(sk)',
            )
            transact.put(
                item={
                    'id': new_image['id'],
                    'sk': 'METADATA#SUBSCRIPTION_COVERED',
                    'org_id': new_image['org_id'],
                    'billing_day': terms['billing_day'],
                    'created_at': now_,
                },
                cond_expr='attribute_not_exists(sk)',
            )
            transact.delete(
                key=KeyPair(
                    pk=new_image['id'],
                    sk='parent_vacancy',
                ),
            )
    except Exception:
        return False
    else:
        return True
