import requests
from aws_lambda_powertools.utilities.data_classes import (
    DynamoDBStreamEvent,
    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
from config import API_URL, COURSE_TABLE

course_layer = DynamoDBPersistenceLayer(COURSE_TABLE, dynamodb_client)


@event_source(data_class=DynamoDBStreamEvent)
def lambda_handler(event: DynamoDBStreamEvent, context: LambdaContext) -> bool:
    r = requests.get(f'{API_URL}/courses.json')
    r.raise_for_status()

    data = r.json()
    now_ = now()

    with course_layer.transact_writer() as transact:
        for course in data:
            transact.update(
                key=KeyPair(course['id'], '0'),
                update_expr='SET metadata__unit_price = :unit_price, \
                             updated_at = :updated_at',
                expr_attr_values={
                    ':unit_price': course['metadata']['unit_price'],
                    ':updated_at': now_,
                },
            )

    return True
