import json
from http import HTTPMethod, HTTPStatus

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

from ..conftest import HttpApiProxy, LambdaContext


def test_enroll(
    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='/enrollments',
            method=HTTPMethod.POST,
            headers={'X-Tenant': 'cJtK9SsnJhKPyxESe7g3DG'},
            body={
                'items': [
                    # existing enrollment, must fail
                    {
                        'user': {
                            'id': '5OxmMjL-ujoR5IMGegQz',
                            'name': 'Sérgio R Siqueira',
                            'email': 'sergio@somosbeta.com.br',
                            'cpf': '07879819908',
                        },
                        'course': {
                            'id': '6d69a34a-cefd-40aa-a89b-dceb694c3e61',
                            'name': 'pytest',
                        },
                    },
                    {
                        'user': {
                            'id': '9a41e867-55e1-4573-bd27-7b5d1d1bcfde',
                            'name': 'Tiago Maciel',
                            'email': 'tiago@somosbeta.com.br',
                            'cpf': '08679004901',
                        },
                        'course': {
                            'id': '6d69a34a-cefd-40aa-a89b-dceb694c3e61',
                            'name': 'pytest',
                        },
                        'deduplication_window': {
                            'offset_days': 60,
                        },
                        'vacancy': {
                            'id': 'vacancies#cJtK9SsnJhKPyxESe7g3DG',
                            'sk': '3CNrFB9dy2RLit2pdeUWy4#8c9b55ef-e988-43ee-b2da-8594850605d7',
                        },
                    },
                ],
            },
        ),
        lambda_context,
    )

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

    fail, succ = json.loads(r['body'])
    assert fail['cause'] == {
        'type': 'DeduplicationConflictError',
        'message': 'Enrollment already exists',
    }

    enrollment = dynamodb_persistence_layer.collection.get_items(
        TransactKey(
            '8c9b55ef-e988-43ee-b2da-8594850605d7',
        )
        + SortKey('0')
        + SortKey('parent_vacancy', path_spec='vacancy')
        + SortKey('related_ids#order', path_spec='order_id')
        + SortKey('related_ids#user', path_spec='user_id'),
    )

    assert enrollment['user'] == {
        'name': 'Tiago Maciel',
        'cpf': '08679004901',
        'id': '9a41e867-55e1-4573-bd27-7b5d1d1bcfde',
        'email': 'tiago@somosbeta.com.br',
    }

    assert enrollment['metadata__related_ids'] == {
        'USER#9a41e867-55e1-4573-bd27-7b5d1d1bcfde',
        'ORG#cJtK9SsnJhKPyxESe7g3DG',
        'ORDER#3CNrFB9dy2RLit2pdeUWy4',
    }

    assert succ['output']['id'] == '8c9b55ef-e988-43ee-b2da-8594850605d7'
    assert enrollment['related_ids#order'] == '3CNrFB9dy2RLit2pdeUWy4'
    assert enrollment['parent_vacancy'] == {
        'sk': '3CNrFB9dy2RLit2pdeUWy4#8c9b55ef-e988-43ee-b2da-8594850605d7',
        'id': 'vacancies#cJtK9SsnJhKPyxESe7g3DG',
    }


def test_enroll_vacancy(
    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='/enrollments',
            method=HTTPMethod.POST,
            headers={'X-Tenant': 'cJtK9SsnJhKPyxESe7g3DG'},
            body={
                'items': [
                    {
                        'user': {
                            'id': '9a41e867-55e1-4573-bd27-7b5d1d1bcfde',
                            'name': 'Tiago Maciel',
                            'email': 'tiago@somosbeta.com.br',
                            'cpf': '08679004901',
                        },
                        'course': {
                            'id': '6d69a34a-cefd-40aa-a89b-dceb694c3e61',
                            'name': 'pytest',
                        },
                        'deduplication_window': {
                            'offset_days': 60,
                        },
                        'vacancy': {
                            'id': 'vacancies#cJtK9SsnJhKPyxESe7g3DG',
                            'sk': '3CNrFB9dy2RLit2pdeUWy4#does_not_exist',
                        },
                    },
                ],
            },
        ),
        lambda_context,
    )

    assert r['statusCode'] == HTTPStatus.OK
    fail, *_ = json.loads(r['body'])
    assert fail['cause'] == {
        'type': 'VacancyDoesNotExistError',
        'message': 'Vacancy does not exist',
    }


def test_vacancies(
    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='/enrollments/vacancies',
            method=HTTPMethod.GET,
            headers={'X-Tenant': '*'},
        ),
        lambda_context,
    )

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


def test_cancel_enrollment(
    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='/enrollments/43ea4475-c369-4f90-b576-135b7df5106b/cancel',
            method=HTTPMethod.PATCH,
            headers={'X-Tenant': '*'},
            body={
                'id': '43ea4475-c369-4f90-b576-135b7df5106b',
                'lock_hash': 'f8f7996aa99d50eb85266be5a9fca1db',
                'course': {
                    'id': '123',
                    'name': 'NR-10',
                    'time_in_days': 720,
                },
                'vacancy': {
                    'sk': 'QV4sXY3DvSTUMGJ4QqsrwJ#43ea4475-c369-4f90-b576-135b7df5106b',
                    'id': 'vacancies#cJtK9SsnJhKPyxESe7g3DG',
                },
            },
        ),
        lambda_context,
    )

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

    enrollment = dynamodb_persistence_layer.collection.get_item(
        KeyPair('43ea4475-c369-4f90-b576-135b7df5106b', '0')
    )
    assert enrollment['status'] == 'CANCELED'

    vacancies = dynamodb_persistence_layer.collection.query(
        PartitionKey(ComposeKey('cJtK9SsnJhKPyxESe7g3DG', 'vacancies'))
    )
    assert len(vacancies['items']) == 2
