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

import konviva

logger = Logger(__name__)


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    changes = event.detail['changes']
    user_id = new_image['metadata__konviva_user_id']

    payload = {}
    for attr in changes:
        match attr:
            case 'name':
                payload.update(NomeUsuario=new_image['name'])
            case 'email':
                payload.update(
                    Email=new_image['email'],
                    Login=new_image['email'],
                )
            case 'cpf':
                payload.update(CPF=new_image['cpf'])

    try:
        r = konviva.update_user(id=user_id, **payload)
    except Exception as exc:
        logger.exception(exc)
        return False
    else:
        logger.info('User updated', result=r, payload=payload)
        return True
