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

from boto3clients import dynamodb_client
from config import ELASTIC_CONN, 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

from .vacancies import router as vacancies

__all__ = ['vacancies']


router = Router()
elastic_client = Elasticsearch(**ELASTIC_CONN)
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
user_collect = DynamoDBCollection(user_layer)


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


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

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

    return payload
