import json
from http import HTTPMethod, HTTPStatus

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

from ..conftest import HttpApiProxy, LambdaContext

YEAR_DAYS = 365


def test_get_courses(
    mock_app,
    dynamodb_seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/courses',
            method=HTTPMethod.GET,
            headers={'X-Tenant': '*'},
        ),
        lambda_context,
    )

    print(r)


def test_post_course(
    mock_app,
    dynamodb_seeds,
    dynamodb_persistence_layer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = mock_app.lambda_handler(
        http_api_proxy(
            raw_path='/courses',
            method=HTTPMethod.POST,
            headers={'X-Tenant': '*'},
            body={
                'name': 'pytest',
                'access_period': YEAR_DAYS,
                'cert': {
                    'exp_interval': YEAR_DAYS * 2,
                },
            },
        ),
        lambda_context,
    )

    assert 'id' in json.loads(r['body'])
    assert r['statusCode'] == HTTPStatus.CREATED

    collection = dynamodb_persistence_layer.collection
    logs = collection.query(
        PartitionKey(
            ComposeKey('5OxmMjL-ujoR5IMGegQz', prefix='log', delimiter=':'),
        )
    )
    assert len(logs['items']) == 3


def test_put_course(
    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='/courses/90d7f0d2-d9a4-4467-a31c-f9a7955964cf',
            method=HTTPMethod.PUT,
            headers={'X-Tenant': '*'},
            body={
                'id': '90d7f0d2-d9a4-4467-a31c-f9a7955964cf',
                'name': 'pytest',
                'access_period': YEAR_DAYS,
                'cert': {
                    'exp_interval': YEAR_DAYS * 2,
                },
            },
        ),
        lambda_context,
    )
    assert r['statusCode'] == HTTPStatus.OK

    collection = dynamodb_persistence_layer.collection
    course = collection.get_item(KeyPair('90d7f0d2-d9a4-4467-a31c-f9a7955964cf', '0'))
    assert course['name'] == 'pytest'
