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.email_ import Message
from layercake.strutils import first_word

from boto3clients import sesv2_client
from config import EMAIL_SENDER

SUBJECT = 'Por favor, verifique seu endereço de email na EDUSEG®'
MESSAGE = """
Oi {first_name}, tudo bem?<br/><br/>

Para proteger sua conta na EDUSEG, precisamos apenas verificar seu
endereço de email: {email}.<br/><br/>

<a href="https://scorm.eduseg.workers.dev/settings/emails/{code}/verify">
👉 Clique aqui para verificar endereço de email
</a>
"""

logger = Logger(__name__)


@event_source(data_class=EventBridgeEvent)
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    first_name = first_word(new_image['name'])
    # Key pattern `EMAIL_VERIFICATION#{hash}`
    *_, hash = new_image['sk'].split('#')

    emailmsg = Message(
        from_=EMAIL_SENDER,
        to=(new_image['name'], new_image['email']),
        subject=SUBJECT,
    )
    emailmsg.add_alternative(
        MESSAGE.format(
            first_name=first_name,
            email=new_image['email'],
            code=hash,
        )
    )

    try:
        sesv2_client.send_email(
            Content={
                'Raw': {
                    'Data': emailmsg.as_bytes(),
                },
            }
        )
        logger.info('Email sent')
    except Exception as exc:
        logger.exception(exc)
        return False
    else:
        return True
