import json

from aws_lambda_powertools.event_handler.api_gateway import Router
from aws_lambda_powertools.event_handler.exceptions import (
    BadRequestError,
)
from elasticsearch import Elasticsearch
from layercake.dynamodb import (
    DynamoDBCollection,
    DynamoDBPersistenceLayer,
    KeyPair,
)

import elastic
from boto3clients import dynamodb_client
from config import ELASTIC_CONN, ORDER_TABLE

router = Router()
order_layer = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)
order_collect = DynamoDBCollection(order_layer, exc_cls=BadRequestError)
elastic_client = Elasticsearch(**ELASTIC_CONN)


@router.get('/', compress=True, tags=['Order'])
def get_orders():
    event = router.current_event
    query = event.get_query_string_value('query', '{}')
    page_size = event.get_query_string_value('page_size', '25')

    return elastic.search(  # type: ignore
        index=ORDER_TABLE,
        page_size=int(page_size),
        query=json.loads(query),
        elastic_client=elastic_client,
    )


@router.get(
    '/<id>',
    compress=True,
    tags=['Order'],
    summary='Get order',
)
def get_order(id: str):
    return order_collect.get_item(KeyPair(id, '0'))
