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 DynamoDBPersistenceLayer, KeyPair

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

from .emails import TEMPLATES, send_email

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


@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()
    pk, sk = old_image['id'], old_image['sk']
    event_name = sk.removeprefix('SCHEDULE#').lower()
    template = TEMPLATES[event_name]

    # If email is missing, use enrollment email
    if 'email' not in old_image:
        r = dyn.get_item(KeyPair(pk=old_image['id'], sk='0'))
        old_image['name'] = r['user']['name']
        old_image['email'] = r['user']['email']
        old_image['course'] = r['course']['name']

    try:
        send_email(
            to=(old_image['name'], old_image['email']),
            subject=template['subject'],
            message=template['message'],
            context={'course': old_image['course']},
            sender=EMAIL_SENDER,
            sesv2_client=sesv2_client,
        )

        dyn.put_item(
            item={
                'id': pk,
                'sk': f'{sk}#EXECUTED',
                'created_at': now_,
            }
        )
    except Exception as exc:
        logger.exception(exc)

        dyn.put_item(
            item={
                'id': pk,
                'sk': f'{sk}#FAILED',
                'created_at': now_,
            }
        )

        return False
    else:
        logger.info('Email sent')
        return True
