from http import HTTPMethod, HTTPStatus

from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    KeyPair,
)

from ...conftest import HttpApiProxy, LambdaContext


def test_add_email(
    mock_app,
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users/5OxmMjL-ujoR5IMGegQz/emails',
            method=HTTPMethod.POST,
            body={
                'email': 'sergio+pytest@somosbeta.com.br',
            },
        ),
        lambda_context,
    )

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

    user = dynamodb_persistence_layer.collection.get_item(
        KeyPair('5OxmMjL-ujoR5IMGegQz', '0')
    )
    assert user['emails'] == {
        'sergio@somosbeta.com.br',
        'osergiosiqueira@gmail.com',
        'sergio+pytest@somosbeta.com.br',
    }


def test_update_email(
    mock_app,
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users/5OxmMjL-ujoR5IMGegQz/emails',
            method=HTTPMethod.PATCH,
            body={
                'old_email': 'sergio@somosbeta.com.br',
                'new_email': 'osergiosiqueira@gmail.com',
            },
        ),
        lambda_context,
    )

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

    user = dynamodb_persistence_layer.collection.get_item(
        KeyPair('5OxmMjL-ujoR5IMGegQz', '0')
    )
    assert user['email'] == 'osergiosiqueira@gmail.com'


def test_remove_email(
    mock_app,
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users/5OxmMjL-ujoR5IMGegQz/emails',
            method=HTTPMethod.DELETE,
            body={
                'email': 'osergiosiqueira@gmail.com',
            },
        ),
        lambda_context,
    )

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

    user = dynamodb_persistence_layer.collection.get_item(
        KeyPair('5OxmMjL-ujoR5IMGegQz', '0')
    )
    assert user['emails'] == {
        'sergio@somosbeta.com.br',
    }
