import json
from http import HTTPMethod, HTTPStatus

from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, PartitionKey

from ...conftest import HttpApiProxy, LambdaContext


def test_enroll(
    app,
    seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/enrollments',
            method=HTTPMethod.POST,
            body={
                'org_id': '2a8963fc-4694-4fe2-953a-316d1b10f1f5',
                'enrollments': [
                    {
                        'id': '44ff9ac1-a7cd-447b-a284-53cdc5929d7f',
                        'user': {
                            'id': '15bacf02-1535-4bee-9022-19d106fd7518',
                            'name': 'Eddie Vedder',
                            'email': 'eddie@pearljam.band',
                            'cpf': '07879819908',
                        },
                        'course': {
                            'id': 'c27d1b4f-575c-4b6b-82a1-9b91ff369e0b',
                            'name': 'NR-18 PEMT Plataforma Móvel de Trabalho Aéreo',
                            'access_period': '360',
                            'unit_price': '149',
                        },
                        'scheduled_for': '2028-01-01',
                    },
                    {
                        'id': 'd0349bbe-cef3-44f7-b20e-3cb4476ab4c5',
                        'user': {
                            'id': '15bacf02-1535-4bee-9022-19d106fd7518',
                            'name': 'Sérgio R Siqueira',
                            'email': 'sergio@somosbeta.com.br',
                            'cpf': '07879819908',
                        },
                        'course': {
                            'id': '9b1bd8e1-b6da-4f68-9a83-c8d5b8f3b628',
                            'name': 'CIPA',
                            'access_period': '360',
                            'unit_price': '99',
                        },
                        'deduplication_window': {
                            'offset_days': '45',
                        },
                    },
                ],
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.OK
    body = json.loads(r['body'])
    submission = dynamodb_persistence_layer.get_item(KeyPair(body['id'], body['sk']))
    assert submission['sk'] == body['sk']

    print(body)

    enrolled = dynamodb_persistence_layer.collection.query(
        PartitionKey('d0349bbe-cef3-44f7-b20e-3cb4476ab4c5')
    )

    assert len(enrolled['items']) == 7

    scheduled = dynamodb_persistence_layer.collection.query(
        PartitionKey('SCHEDULED#ORG#2a8963fc-4694-4fe2-953a-316d1b10f1f5')
    )

    assert len(scheduled['items']) == 1
