import json
from http import HTTPMethod, HTTPStatus

from layercake.dynamodb import (
    DynamoDBCollection,
    DynamoDBPersistenceLayer,
    KeyPair,
    SortKey,
    TransactKey,
)

from ..conftest import HttpApiProxy, LambdaContext


def test_update_user_cpf(
    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',
            method=HTTPMethod.PUT,
            body={
                'name': 'Sérgio Siqueira',
                'cpf': '26886156020',
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.OK

    collect = DynamoDBCollection(dynamodb_persistence_layer)
    user = collect.get_items(
        TransactKey('5OxmMjL-ujoR5IMGegQz')
        + SortKey('0')
        + SortKey('last_profile_edit')
    )
    assert 'last_profile_edit' in user


def test_update_user_name(
    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',
            method=HTTPMethod.PUT,
            body={
                'name': 'Sérgio R Siqueira',
                'cpf': '07879819908',
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.OK


def test_update_user_conflict_cpf(
    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',
            method=HTTPMethod.PUT,
            body={
                'name': 'Sérgio Siqueira',
                'cpf': '08679004901',
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.BAD_REQUEST


def test_get_emails(
    mock_app,
    dynamodb_seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users/5OxmMjL-ujoR5IMGegQz/emails',
            method=HTTPMethod.GET,
        ),
        lambda_context,
    )

    # This data was added from seeds
    assert json.loads(r['body']) == {
        'items': [
            {
                'email_verified': True,
                'mx_record_exists': True,
                'sk': 'sergio@somosbeta.com.br',
                'email_primary': True,
                'id': '5OxmMjL-ujoR5IMGegQz',
                'create_date': '2019-03-25T00:00:00-03:00',
                'update_date': '2023-11-09T12:13:04.308986-03:00',
            },
            {
                'email_verified': True,
                'mx_record_exists': True,
                'sk': 'osergiosiqueira@gmail.com',
                'email_primary': False,
                'id': '5OxmMjL-ujoR5IMGegQz',
                'create_date': '2019-03-25T00:00:00-03:00',
                'update_date': '2023-11-09T12:13:04.308986-03:00',
            },
        ],
        'last_key': None,
    }


def test_get_orgs(
    mock_app,
    dynamodb_seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users/5OxmMjL-ujoR5IMGegQz/orgs',
            method=HTTPMethod.GET,
        ),
        lambda_context,
    )

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


def test_get_logs(
    mock_app,
    dynamodb_seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users/5OxmMjL-ujoR5IMGegQz/logs',
            method=HTTPMethod.GET,
        ),
        lambda_context,
    )

    # This data was added from seeds
    assert r['statusCode'] == HTTPStatus.OK
    assert json.loads(r['body']) == {
        'items': [
            {
                'sk': '2024-02-08T16:42:33.776409-03:00',
                'action': 'OPEN_EMAIL',
                'id': '5OxmMjL-ujoR5IMGegQz',
            },
            {
                'sk': '2019-03-25T00:00:00-03:00',
                'action': 'CLICK_EMAIL',
                'id': '5OxmMjL-ujoR5IMGegQz',
            },
        ],
        'last_key': None,
    }


def test_post_user(
    mock_app,
    dynamodb_client,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/users',
            method=HTTPMethod.POST,
            body={
                'name': 'Sérgio R Siqueira',
                'email': 'sergio@somosbeta.com.br',
                'cpf': '07879819908',
            },
        ),
        lambda_context,
    )

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


def test_post_email(
    mock_app,
    dynamodb_client,
    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

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


def test_patch_email(
    mock_app,
    dynamodb_client,
    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_delete_email(
    mock_app,
    dynamodb_client,
    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

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