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 NotFoundError
from aws_lambda_powertools.event_handler.openapi.params import Body
from layercake.dateutils import now
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
from passlib.hash import pbkdf2_sha256

from api_gateway import JSONResponse
from boto3clients import dynamodb_client
from config import USER_TABLE

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


class UserNotFoundError(NotFoundError): ...


@router.post('/<user_id>/password')
def password(
    user_id: str,
    new_password: Annotated[str, Body(min_length=6, embed=True)],
):
    with dyn.transact_writer() as transact:
        transact.condition(
            key=KeyPair(user_id, '0'),
            cond_expr='attribute_exists(sk)',
            exc_cls=UserNotFoundError,
        )
        transact.put(
            item={
                'id': user_id,
                'sk': 'PASSWORD',
                'hash': pbkdf2_sha256.hash(new_password),
                'created_at': now(),
            }
        )

    return JSONResponse(status_code=HTTPStatus.NO_CONTENT)
