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 = '{first_name} você foi cadastrado na EDUSEG®'
MESSAGE = """
Oi {first_name}, tudo bem?<br/><br/>

Sua conta foi criada na EDUSEG pela empresa <b>{org_name}</b>.<br/><br/>

<a href="https://scorm.eduseg.workers.dev/signup?uid={user_id}&code={code}">
👉 Clique aqui para fazer seu primeiro acesso
</a>
"""

logger = Logger(__name__)


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

    emailmsg = Message(
        from_=EMAIL_SENDER,
        to=(new_image['name'], new_image['email']),
        subject=SUBJECT.format(first_name=first_name),
    )
    emailmsg.add_alternative(
        MESSAGE.format(
            user_id=new_image['id'],
            first_name=first_name,
            org_name=new_image.get('org_name'),
            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
