import json
from http import HTTPMethod, HTTPStatus

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

from ...conftest import HttpApiProxy, LambdaContext


def test_add_user(
    app,
    seeds,
    http_api_proxy: HttpApiProxy,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/orgs/f6000f79-6e5c-49a0-952f-3bda330ef278/users',
            method=HTTPMethod.POST,
            body={
                'user': {
                    'name': 'Scott Weiland',
                    'email': 'scott@stonetemplopilots.com',
                    'cpf': '40245650016',
                },
                'org': {
                    'name': 'pytest',
                    'cnpj': '04978826000180',
                },
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.CREATED
    r = dynamodb_persistence_layer.collection.query(
        PartitionKey('orgmembers#f6000f79-6e5c-49a0-952f-3bda330ef278')
    )
    user_id = r['items'][0]['sk']
    user = dynamodb_persistence_layer.collection.get_items(
        TransactKey(user_id)
        + SortKey('0')
        + SortKey('emails#scott@stonetemplopilots.com')
    )
    assert user['name'] == 'Scott Weiland'
    assert 'email' in user
    assert 'email_verified' in user
    # assert 'created_at' in user
    # assert 'org_id' in user
    assert 'tenant_id' in user
    assert 'emails#scott@stonetemplopilots.com' in user


def test_user_exists(
    app,
    seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/orgs/2a8963fc-4694-4fe2-953a-316d1b10f1f5/users',
            method=HTTPMethod.POST,
            body={
                'user': {
                    'name': 'Sérgio R Siqueira',
                    'email': 'sergio@somosbeta.com.br',
                    'cpf': '07879819908',
                },
                'org': {
                    'name': 'pytest',
                    'cnpj': '04978826000180',
                },
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.NO_CONTENT

    r = dynamodb_persistence_layer.collection.query(
        PartitionKey('orgmembers#2a8963fc-4694-4fe2-953a-316d1b10f1f5')
    )
    user_id = r['items'][0]['sk']

    user = dynamodb_persistence_layer.collection.get_items(
        TransactKey(user_id)
        + SortKey('0')
        + SortKey('emails#sergio@somosbeta.com.br', rename_key='email')
        + SortKey('orgs#2a8963fc-4694-4fe2-953a-316d1b10f1f5', rename_key='org')
    )
    assert 'mx_record_exists' in user['email']
    assert 'cnpj' in user['org']


def test_user_conflict(
    app,
    seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/orgs/f6000f79-6e5c-49a0-952f-3bda330ef278/users',
            method=HTTPMethod.POST,
            body={
                'user': {
                    'name': 'Sérgio R Siqueira',
                    'email': 'sergio@somosbeta.com.br',
                    'cpf': '07879819908',
                },
                'org': {
                    'name': 'Banco do Brasil',
                    'cnpj': '00000000000191',
                },
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.CONFLICT


def test_org_not_found(
    app,
    seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/orgs/123/users',
            method=HTTPMethod.POST,
            body={
                'user': {
                    'name': 'Sérgio R Siqueira',
                    'email': 'sergio@somosbeta.com.br',
                    'cpf': '07879819908',
                },
                'org': {
                    'name': 'Banco do Brasil',
                    'cnpj': '00000000000191',
                },
            },
        ),
        lambda_context,
    )
    body = json.loads(r['body'])
    assert body['type'] == 'OrgNotFoundError'


def test_unlink(
    app,
    seeds,
    http_api_proxy: HttpApiProxy,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/orgs/f6000f79-6e5c-49a0-952f-3bda330ef278/users/15bacf02-1535-4bee-9022-19d106fd7518',
            method=HTTPMethod.DELETE,
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.NO_CONTENT

    members = dynamodb_persistence_layer.collection.query(
        PartitionKey('orgmembers#f6000f79-6e5c-49a0-952f-3bda330ef278')
    )
    assert len(members['items']) == 0

    orgs = dynamodb_persistence_layer.collection.query(
        KeyPair('15bacf02-1535-4bee-9022-19d106fd7518', 'orgs#')
    )
    assert len(orgs['items']) == 0
