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, ttl
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey

from boto3clients import dynamodb_client
from config import (
    COURSE_TABLE,
    ENROLLMENT_TABLE,
)

logger = Logger(__name__)
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
course_layer = DynamoDBPersistenceLayer(COURSE_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']
    now_ = now()
    enrollment_id = new_image['id']
    user = new_image['user']
    course_name = new_image['course']['name']

    # Post-migration: after removing the stopgap file `patch_course_metadata.py`,
    # use `access_expires_at` from `new_image`
    access_period = int(
        course_layer.collection.get_item(
            KeyPair(
                pk=new_image['course']['id'],
                sk=SortKey('0', path_spec='access_period'),
            ),
        )
    )

    with enrollment_layer.transact_writer() as transact:
        transact.put(
            item={
                'id': enrollment_id,
                'sk': 'SCHEDULE#REMINDER_NO_ACCESS_AFTER_3_DAYS',
                'name': user['name'],
                'email': user['email'],
                'course': course_name,
                'created_at': now_,
                'ttl': ttl(start_dt=now_, days=3),
            },
        )

        # Schedule the event to add `access_expired` after the access period ends
        # transact.put(
        #     item={
        #         'id': enrollment_id,
        #         'sk': 'SCHEDULE#SET_ACCESS_EXPIRED',
        #         'created_at': now_,
        #         'ttl': ttl(start_dt=now_, days=access_period),
        #     },
        # )

        transact.put(
            item={
                'id': enrollment_id,
                'sk': 'SCHEDULE#REMINDER_ACCESS_PERIOD_BEFORE_30_DAYS',
                'name': user['name'],
                'email': user['email'],
                'course': course_name,
                'created_at': now_,
                'ttl': ttl(start_dt=now_, days=access_period - 30),
            },
        )

    return True
