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.dateutils import now
from layercake.dynamodb import ComposeKey, DynamoDBPersistenceLayer, KeyPair
from layercake.strutils import first_word, truncate_str

from boto3clients import dynamodb_client, sesv2_client
from config import (
    EMAIL_SENDER,
    ENROLLMENT_TABLE,
)
from email_ import Message

logger = Logger(__name__)
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)


SUBJECT = 'Seu curso de {course} está esperando por você na EDUSEG®'
MESSAGE = """
Oi {first_name}, tudo bem?<br/><br/>

Há 3 dias você foi matriculado no curso de <b>{course}</b>, mas ainda não iniciou.<br/>
Não perca a oportunidade de aprender e aproveitar ao máximo seu curso!<br/><br/>

Clique no link abaixo para acessar seu curso:
<a href="https://saladeaula.digital">https://saladeaula.digital</a>
"""


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    old_image = event.detail['old_image']
    now_ = now()

    # Post-migration: Remove the following lines
    if 'email' not in old_image:
        data = enrollment_layer.get_item(KeyPair(old_image['id'], '0'))
        old_image['name'] = data['user']['name']
        old_image['email'] = data['user']['email']
        old_image['course'] = data['course']['name']

    emailmsg = Message(
        from_=EMAIL_SENDER,
        to=(
            old_image['name'],
            old_image['email'],
        ),
        subject=SUBJECT.format(course=truncate_str(old_image['course'])),
    )
    emailmsg.add_alternative(
        MESSAGE.format(
            first_name=first_word(old_image['name']),
            course=old_image['course'],
        )
    )

    try:
        sesv2_client.send_email(
            Content={
                'Raw': {
                    'Data': emailmsg.as_bytes(),
                },
            }
        )
    except Exception as exc:
        logger.exception(exc)
        enrollment_layer.put_item(
            item={
                'id': old_image['id'],
                'sk': ComposeKey('failed', 'schedules#reminder_no_access_3_days'),
                # Post-migration: Uncomment the following line
                # 'sk': ComposeKey('failed', old_image['sk']),
                'created_at': now_,
            }
        )

        return False
    else:
        enrollment_layer.put_item(
            item={
                'id': old_image['id'],
                'sk': ComposeKey('completed', 'schedules#reminder_no_access_3_days'),
                # Post-migration: Uncomment the following line
                # 'sk': ComposeKey('completed', old_image['sk']),
                'created_at': now_,
            }
        )

        return True
