from aws_lambda_powertools.event_handler.api_gateway import Router
from layercake.dynamodb import (
    DynamoDBCollection,
    DynamoDBPersistenceLayer,
    KeyPair,
    PrefixKey,
)

import konviva
from boto3clients import dynamodb_client
from middlewares import AuthenticatedUser
from settings import USER_TABLE

router = Router()
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
collect = DynamoDBCollection(user_layer)


LIMIT = 25


@router.get('/', include_in_schema=False)
def me():
    user: AuthenticatedUser = router.context['authenticated_user']
    acls = collect.get_items(
        KeyPair(user.id, PrefixKey('acls')),
        limit=LIMIT,
    )
    workspaces = collect.get_items(
        KeyPair(user.id, PrefixKey('orgs')),
        limit=LIMIT,
    )

    return {
        'acls': acls['items'],
        'workspaces': workspaces['items'],
    }


@router.get('/konviva', include_in_schema=False)
def konviva_():
    user: AuthenticatedUser = router.context['authenticated_user']
    token = konviva.token(user.email)

    return {'redirect_uri': konviva.redirect_uri(token)}
