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

import konviva
from boto3clients import dynamodb_client
from config import USER_TABLE
from middlewares import User

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


LIMIT = 25


@router.get('/', include_in_schema=False)
def settings():
    user: User = router.context['user']
    acls = user_layer.collection.query(
        KeyPair(user.id, PrefixKey('acls')),
        limit=LIMIT,
    )
    tenants = user_layer.collection.query(
        KeyPair(user.id, PrefixKey('orgs')),
        limit=LIMIT,
    )

    return {
        'acls': acls['items'],
        # Note: Ensure compatibility with search on React's tenant menu
        'tenants': [x | {'id': x['sk'], 'sk': '0'} for x in tenants['items']],
    }


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

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