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 glom import glom
from layercake.dateutils import now
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair

import konviva
from boto3clients import dynamodb_client
from config import USER_TABLE

logger = Logger(__name__)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)


class UserNotFoundError(Exception): ...


@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()

    try:
        user_id = konviva.create_user(
            id=new_image['id'],
            name=new_image['name'],
            email=new_image['email'],
            cpf=new_image.get('cpf', None),
        )
    except konviva.EmailAlreadyExists as exc:
        logger.exception(exc, email=new_image['email'])

        r = konviva.get_users_by_email(new_image['email'])
        user_id = glom(r, '0.IDUsuario')

        if not r:
            raise UserNotFoundError()
    except Exception:
        raise

    with user_layer.transact_writer() as transact:
        transact.update(
            key=KeyPair(new_image['id'], '0'),
            update_expr='SET metadata__konviva_user_id = :user_id, \
                        updated_at = :updated_at',
            expr_attr_values={
                ':user_id': user_id,
                ':updated_at': now_,
            },
            cond_expr='attribute_exists(sk)',
        )
        # Post-migration: remove the following line
        transact.put(
            item={
                'id': new_image['id'],
                'sk': 'konviva',
                'konvivaId': user_id,
                'created_at': now_,
            }
        )

    return True
