import urllib.parse as parse
from http import HTTPStatus
from typing import Annotated

from aws_lambda_powertools.event_handler.api_gateway import Router
from aws_lambda_powertools.event_handler.exceptions import (
    BadRequestError as PowertoolsBadRequestError,
)
from layercake.dynamodb import (
    DynamoDBCollection,
    DynamoDBPersistenceLayer,
    MissingError,
    SortKey,
    TransactKey,
)
from layercake.extra_types import CpfStr, NameStr
from meilisearch import Client as Meilisearch
from pydantic import UUID4, BaseModel, StringConstraints

import cognito
import meili
from api_gateway import JSONResponse
from boto3clients import dynamodb_client, idp_client
from config import MEILISEARCH_API_KEY, MEILISEARCH_HOST, USER_POOOL_ID, USER_TABLE
from middlewares import AuditLogMiddleware, Tenant, TenantMiddleware
from models import User
from rules.user import update_user

from .emails import router as emails
from .logs import router as logs
from .orgs import router as orgs

__all__ = ['logs', 'emails', 'orgs']


class BadRequestError(MissingError, PowertoolsBadRequestError):
    pass


router = Router()
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
user_collect = DynamoDBCollection(user_layer, exc_cls=BadRequestError)
meili_client = Meilisearch(MEILISEARCH_HOST, MEILISEARCH_API_KEY)  # noqa: F821


@router.get(
    '/',
    compress=True,
    tags=['User'],
    middlewares=[
        TenantMiddleware(user_layer.collection),
    ],
    summary='Get users',
)
def get_users():
    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(USER_TABLE).search(
        query,
        {
            'sort': [sort],
            'locales': ['pt'],
            'page': page,
            'hitsPerPage': hits_per_page,
            'filter': meili.encode(filter_),
        },
    )


@router.post(
    '/',
    compress=True,
    tags=['User'],
    summary='Create user',
    middlewares=[AuditLogMiddleware('USER_ADD', user_collect)],
)
def post_user(payload: User):
    return JSONResponse(status_code=HTTPStatus.CREATED)


class UserData(BaseModel):
    name: NameStr
    cpf: CpfStr


@router.put(
    '/<id>',
    compress=True,
    tags=['User'],
    summary='Update user',
    middlewares=[
        AuditLogMiddleware('USER_UPDATE', user_collect, ('id', 'name', 'new_cpf'))
    ],
)
def put_user(id: str, payload: UserData):
    update_user(
        {
            'id': id,
            'name': payload.name,
            'cpf': payload.cpf,
        },
        persistence_layer=user_layer,
    )
    return JSONResponse(
        body={
            'id': id,
            'name': payload.name,
            'new_cpf': payload.cpf,
        },
        status_code=HTTPStatus.OK,
    )


@router.get('/<id>', compress=True, tags=['User'], summary='Get user')
def get_user(id: str):
    return user_collect.get_items(
        TransactKey(id) + SortKey('0') + SortKey('last_profile_edit')
    )


class Password(BaseModel):
    cognito_sub: UUID4
    new_password: Annotated[str, StringConstraints(min_length=6)]


@router.post(
    '/<id>/password',
    compress=True,
    tags=['User'],
    include_in_schema=False,
    middlewares=[
        AuditLogMiddleware('PASSWORD_RESET', user_collect, ('id', 'cognito_sub'))
    ],
)
def password(id: str, payload: Password):
    cognito.admin_set_user_password(
        username=str(payload.cognito_sub),
        password=payload.new_password,
        user_pool_id=USER_POOOL_ID,
        idp_client=idp_client,
    )
    return JSONResponse(
        body={
            'id': id,
            'cognito_sub': payload.cognito_sub,
        },
        status_code=HTTPStatus.OK,
    )


@router.get('/<sub>/idp', compress=True, include_in_schema=False)
def get_idp(sub: str):
    return cognito.admin_get_user(
        sub=sub,
        user_pool_id=USER_POOOL_ID,
        idp_client=idp_client,
    )
