import json
import pprint
from base64 import b64encode
from http import HTTPMethod, HTTPStatus
from urllib.parse import urlencode

import pytest
from layercake.dynamodb import DynamoDBPersistenceLayer

from ..conftest import HttpApiProxy, LambdaContext

CLIENT_ID = '1db63660-063d-4280-b2ea-388aca4a9459'
CLIENT_SECRET = '1nFD8alDbGHgc3g1RLY960xyRJVee0SlMoIB0MUlSuiJy28W'
AUTH = b64encode(f'{CLIENT_ID}:{CLIENT_SECRET}'.encode()).decode()


@pytest.fixture
def token(
    app,
    seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/token',
            method=HTTPMethod.POST,
            headers={
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': f'Basic {AUTH}',
            },
            body=urlencode(
                {
                    'grant_type': 'authorization_code',
                    'redirect_uri': 'https://localhost/callback',
                    'code': 'kyqp3oSuRFTfuBaCmq3XOgGWg67l42Kt3D6xPEj7Yd3MLdi9',
                    'code_verifier': '9072df2d3709425993e733f38fb27a825b8860e699364ce9abafdf51077c0bdb4e456ddb741147a4bec4eeda782d92cc',
                }
            ),
        ),
        lambda_context,
    )
    return json.loads(r['body'])


def test_revoke(
    app,
    token,
    seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    http_api_proxy: HttpApiProxy,
    lambda_context: LambdaContext,
):
    tokens = dynamodb_persistence_layer.query(
        key_cond_expr='#pk = :pk',
        expr_attr_name={
            '#pk': 'id',
        },
        expr_attr_values={
            ':pk': 'OAUTH2#TOKEN',
        },
    )

    assert len(tokens['items']) == 3

    r = app.lambda_handler(
        http_api_proxy(
            raw_path='/revoke',
            method=HTTPMethod.POST,
            headers={
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': f'Basic {AUTH}',
            },
            body=urlencode(
                {
                    'token': token['access_token'],
                    # 'token_type_hint': 'access_token',
                }
            ),
        ),
        lambda_context,
    )

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

    tokens = dynamodb_persistence_layer.query(
        key_cond_expr='#pk = :pk',
        expr_attr_name={
            '#pk': 'id',
        },
        expr_attr_values={
            ':pk': 'OAUTH2#TOKEN',
        },
    )
    assert len(tokens['items']) == 1

    sessions = dynamodb_persistence_layer.query(
        key_cond_expr='#pk = :pk',
        expr_attr_name={
            '#pk': 'id',
        },
        expr_attr_values={
            ':pk': 'SESSION',
        },
    )
    assert len(sessions['items']) == 0
