from http import HTTPMethod

import pytest
from aws_lambda_powertools.event_handler.api_gateway import APIGatewayHttpResolver
from layercake.dynamodb import DynamoDBCollection, DynamoDBPersistenceLayer

from middlewares import AuthenticationMiddleware, TenantMiddleware

from .conftest import HttpApiProxy, LambdaContext


@pytest.fixture
def mock_app(dynamodb_persistence_layer: DynamoDBPersistenceLayer):
    collect = DynamoDBCollection(dynamodb_persistence_layer)
    app = APIGatewayHttpResolver()
    app.use(middlewares=[AuthenticationMiddleware(), TenantMiddleware(collect)])

    @app.get('/')
    def index():
        return app.context.get('tenant')

    return app


def test_tenant_user_auth(
    mock_app,
    dynamodb_seeds,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    # This data was added from seeds
    result = mock_app(
        http_api_proxy(
            raw_path='/',
            method=HTTPMethod.GET,
            headers={'X-Tenant': 'cJtK9SsnJhKPyxESe7g3DG'},
        ),
        lambda_context,
    )

    assert result['body'] == '{"id":"cJtK9SsnJhKPyxESe7g3DG","name":"EDUSEG"}'
    assert result['statusCode'] == 200


def test_tenant_forbidden(
    mock_app,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    result = mock_app(
        http_api_proxy(
            raw_path='/',
            method=HTTPMethod.GET,
            headers={'X-Tenant': 'abc'},
        ),
        lambda_context,
    )

    assert result['statusCode'] == 403
