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 USER_TABLE

user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)


@event_source(data_class=EventBridgeEvent)
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    now_ = now()
    _, tenant = new_image['id'].split('#')

    user_layer.update_item(
        key=KeyPair(new_image['sk'], '0'),
        update_expr='ADD tenant_id :tenant_id SET updated_at = :updated_at',
        expr_attr_values={
            ':tenant_id': {tenant},
            ':updated_at': now_,
        },
    )

    return True
