from http import HTTPStatus

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 (
    DynamoDBPersistenceLayer,
    KeyPair,
    MissingError,
    PrefixKey,
)
from layercake.extra_types import CnpjStr
from pydantic import BaseModel

from api_gateway import JSONResponse
from boto3clients import dynamodb_client
from config import USER_TABLE
from middlewares.audit_log_middleware import AuditLogMiddleware
from rules.user import del_org_member


class BadRequestError(MissingError, PowertoolsBadRequestError): ...


router = Router()
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)


@router.get(
    '/<id>/orgs',
    compress=True,
    tags=['User'],
    summary='Get user orgs',
)
def get_orgs(id: str):
    return user_layer.collection.query(
        KeyPair(id, PrefixKey('orgs')),
        start_key=router.current_event.get_query_string_value('start_key', None),
    )


class Unassign(BaseModel):
    id: str
    name: str
    cnpj: CnpjStr


@router.delete(
    '/<id>/orgs',
    compress=True,
    tags=['User'],
    summary='Delete user org',
    middlewares=[
        AuditLogMiddleware(
            'UNASSIGN_ORG', user_layer.collection, ('id', 'name', 'cnpj')
        )
    ],
)
def delete_org(id: str, payload: Unassign):
    del_org_member(id, org_id=payload.id, persistence_layer=user_layer)
    return JSONResponse(status_code=HTTPStatus.OK, body=payload)
