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 USER_TABLE

logger = Logger(__name__)
dyn = DynamoDBPersistenceLayer(USER_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']
    user_id = new_image['id']
    now_ = now()
    # Post-migration (users): uncommnent the following line
    # r = dyn.collection.query(KeyPair(pk=user_id, sk='ORG#'))
    r = dyn.collection.query(KeyPair(pk=user_id, sk='orgs#'))

    for org in r.get('items', []):
        _, org_id = org['sk'].split('#')

        try:
            dyn.update_item(
                key=KeyPair(
                    pk=org_id,
                    # Post-migration (users): uncommnent the following line
                    # sk=f'ADMIN#{user_id}',
                    sk=f'admins#{user_id}',
                ),
                update_expr='SET #name = :name, \
                                 email = :email, \
                                 updated_at = :now',
                expr_attr_names={
                    '#name': 'name',
                },
                expr_attr_values={
                    ':name': new_image['name'],
                    ':email': new_image['email'],
                    ':now': now_,
                },
                cond_expr='attribute_exists(sk)',
            )
        except Exception:
            logger.info(f'User "{user_id}" does not have admin privileges')

    return True
