import urllib.parse as parse

from aws_lambda_powertools.event_handler.api_gateway import Router
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    SortKey,
    TransactKey,
)
from meilisearch import Client as Meilisearch

import meili
from boto3clients import dynamodb_client
from config import MEILISEARCH_API_KEY, MEILISEARCH_HOST, ORDER_TABLE, USER_TABLE
from middlewares import Tenant, TenantMiddleware

router = Router()
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
order_layer = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)
meili_client = Meilisearch(MEILISEARCH_HOST, MEILISEARCH_API_KEY)


@router.get(
    '/',
    compress=True,
    tags=['Order'],
    middlewares=[
        TenantMiddleware(user_layer.collection),
    ],
)
def get_orders():
    tenant: Tenant = router.context['tenant']
    event = router.current_event
    query = parse.unquote(event.get_query_string_value('q', ''))
    sort = event.get_query_string_value('sort', 'create_date:desc')
    page = int(event.get_query_string_value('page', '1'))
    hits_per_page = int(event.get_query_string_value('hitsPerPage', '25'))
    filter_ = meili.parse(event.get_query_string_value('filter', ''))

    if tenant.id != '*':
        filter_ = [
            {
                'attr': 'tenant_id',
                'op': '=',
                'value': tenant.id,
            },
        ] + filter_

    return meili_client.index(ORDER_TABLE).search(
        query,
        {
            'sort': [sort],
            'locales': ['pt'],
            'page': page,
            'hitsPerPage': hits_per_page,
            'filter': meili.encode(filter_),
        },
    )


@router.get(
    '/<id>',
    compress=True,
    tags=['Order'],
    summary='Get order',
)
def get_order(id: str):
    return order_layer.collection.get_items(
        TransactKey(id)
        + SortKey('0')
        + SortKey('items', path_spec='items')
        + SortKey('address')
        + SortKey('nfse', path_spec='nfse')
        + SortKey('fees', path_spec='fees'),
    )
