import json
from http import HTTPMethod, HTTPStatus

from layercake.dynamodb import DynamoDBPersistenceLayer, PartitionKey

from ...conftest import HttpApiProxy, LambdaContext


def test_add(
    mock_app,
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    org_id = 'cJtK9SsnJhKPyxESe7g3DG'
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users',
            method=HTTPMethod.POST,
            body={
                'name': 'Eddie Van Halen',
                'email': 'eddie@vanhalen.com',
                'cpf': '12974982085',
                'org': {
                    'id': org_id,
                    'name': 'EDUSEG',
                    'cnpj': '15608435000190',
                },
            },
        ),
        lambda_context,
    )
    user = json.loads(r['body'])

    assert r['statusCode'] == HTTPStatus.CREATED

    r = dynamodb_persistence_layer.collection.query(PartitionKey(user['id']))
    assert len(r['items']) == 2

    r = dynamodb_persistence_layer.collection.query(
        PartitionKey(f'orgmembers#{org_id}')
    )
    # 2 items were added from the seed
    assert len(r['items']) == 3


def test_add_existing_user(
    mock_app,
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    org_id = 'cJtK9SsnJhKPyxESe7g3DG'
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users',
            method=HTTPMethod.POST,
            body={
                'name': 'Sérgio Rafael Siqueira',
                'email': 'sergio@somosbeta.com.br',
                'cpf': '07879819908',
                'org': {
                    'id': org_id,
                    'name': 'EDUSEG',
                    'cnpj': '15608435000190',
                },
            },
        ),
        lambda_context,
    )

    r = dynamodb_persistence_layer.collection.query(
        PartitionKey(f'orgmembers#{org_id}')
    )
    # 2 items were added from the seed
    assert len(r['items']) == 3
