from aws_lambda_powertools.event_handler.api_gateway import Router
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    KeyPair,
)
from pydantic import UUID4, BaseModel

from boto3clients import dynamodb_client
from config import ENROLLMENT_TABLE, USER_TABLE
from middlewares.audit_log_middleware import AuditLogMiddleware
from middlewares.authentication_middleware import User
from rules.enrollment import set_status_as_canceled

router = Router()
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)


class Cancel(BaseModel):
    id: UUID4 | str
    lock_hash: str | None = None
    course: dict = {}
    vacancy: dict = {}


@router.patch(
    '/<id>/cancel',
    compress=True,
    tags=['Enrollment'],
    middlewares=[
        AuditLogMiddleware(
            'ENROLLMENT_CANCEL',
            collection=user_layer.collection,
            audit_attrs=('id', 'course'),
        ),
    ],
)
def cancel(id: str, payload: Cancel):
    user: User = router.context['user']

    set_status_as_canceled(
        id,
        lock_hash=payload.lock_hash,
        author={
            'id': user.id,
            'name': user.name,
        },
        course=payload.course,  # type: ignore
        vacancy_key=KeyPair.parse_obj(payload.vacancy),
        persistence_layer=enrollment_layer,
    )

    return payload
