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 email_validator import EmailUndeliverableError, validate_email
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']
    # Post-migration (users): rename `emails` to `EMAIL`
    email = new_image['sk'].removeprefix('emails#')

    return dyn.update_item(
        key=KeyPair(
            pk=new_image['id'],
            sk=new_image['sk'],
        ),
        update_expr='SET mx_record_exists = :bool, \
                         updated_at = :now',
        expr_attr_values={
            ':bool': _mx_record_exists(email),
            ':now': now(),
        },
    )


def _mx_record_exists(email: str) -> bool:
    try:
        validate_email(email, check_deliverability=True)
    except EmailUndeliverableError:
        return False
    else:
        return True
