from http import HTTPStatus

from aws_lambda_powertools.event_handler.api_gateway import Router
from glom import glom
from layercake.funcs import pick
from meilisearch import Client as Meilisearch

from api_gateway import JSONResponse
from config import MEILISEARCH_API_KEY, MEILISEARCH_HOST, USER_TABLE

router = Router()
meili_client = Meilisearch(MEILISEARCH_HOST, MEILISEARCH_API_KEY)


@router.get('/<username>', include_in_schema=False)
def lookup(username: str):
    r = meili_client.index(USER_TABLE).search(f'"{username}"')

    if user := glom(r, 'hits.0', default=None):
        return pick(('id', 'name', 'email', 'cognito__sub'), user)

    return JSONResponse(
        body={'message': 'User not found.'},
        status_code=HTTPStatus.NOT_FOUND,
    )
