from layercake.dateutils import now
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair

from models import Course, Org


def create_course(
    course: Course,
    org: Org,
    /,
    persistence_layer: DynamoDBPersistenceLayer,
):
    now_ = now()

    with persistence_layer.transact_writer() as transact:
        transact.put(
            item={
                'sk': '0',
                'tenant_id': {org.id},
                'created_at': now_,
                **course.model_dump(),
            }
        )
        transact.put(
            item={
                'id': course.id,
                'sk': 'metadata#tenant',
                'org_id': org.id,
                'name': org.name,
                'created_at': now_,
            }
        )

    return True


def update_course(
    id: str,
    course: Course,
    /,
    persistence_layer: DynamoDBPersistenceLayer,
):
    now_ = now()

    with persistence_layer.transact_writer() as transact:
        transact.update(
            key=KeyPair(id, '0'),
            update_expr='SET #name = :name, access_period = :access_period, \
                        cert = :cert, updated_at = :updated_at',
            expr_attr_names={
                '#name': 'name',
            },
            expr_attr_values={
                ':name': course.name,
                ':cert': course.cert.model_dump() if course.cert else None,
                ':access_period': course.access_period,
                ':updated_at': now_,
            },
            cond_expr='attribute_exists(sk)',
        )
    return True
