from http import HTTPStatus

from aws_lambda_powertools.event_handler import Response, content_types
from aws_lambda_powertools.event_handler.api_gateway import Router
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
from layercake.funcs import pick

from settings import ELASTIC_CONN, USER_TABLE

router = Router()
elastic_client = Elasticsearch(**ELASTIC_CONN)


@router.get('/<username>', include_in_schema=False)
def lookup(username: str):
    s = Search(using=elastic_client, index=USER_TABLE).query(
        'bool',
        should=[
            {'term': {'email.keyword': username}},
            {'term': {'cpf.keyword': username}},
        ],
        minimum_should_match=1,
    )

    for hit in s.execute():
        return pick(('id', 'name', 'email', 'cognito:sub'), hit.to_dict())

    return Response(
        content_type=content_types.APPLICATION_JSON,
        status_code=HTTPStatus.NOT_FOUND,
    )
