# Copyright (c) 2021 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

import os
from pprint import pformat

import boto3
import pyfaaster.aws.tools as faaster_aws_tools
import pytest
import requests
from czc.constants import FEATURE_NAME
from toolz.dicttoolz import get_in

logger = faaster_aws_tools.setup_logging(FEATURE_NAME)

cfn = boto3.resource('cloudformation')
api = boto3.client('apigateway')


@pytest.fixture(scope="session")
def tenant():
    return (os.environ['TENANT'], os.environ['PRIVATE_CLIENT_ID'], os.environ['PRIVATE_CLIENT_SECRET'])


@pytest.fixture(scope="session")
def credentials(tenant):
    return {
        'tenant': tenant,
        'password': os.environ['PASSWORD']
    }


@pytest.fixture(scope="session")
def namespace():
    return os.environ['NAMESPACE']


@pytest.fixture(scope="session")
def stack_outputs(namespace):
    stack = cfn.Stack(f'cz-{namespace}-{FEATURE_NAME}')
    outputs = {o['OutputKey']: o['OutputValue']
               for o in stack.outputs}
    logger.debug(outputs)
    return outputs


@pytest.fixture(scope="session")
def private_api_key(namespace):
    keys = api.get_api_keys(nameQuery=f'cz-{namespace}-{FEATURE_NAME}-act-private-api-key', includeValues=True)
    logger.debug(keys)
    return get_in(['items', 0, 'value'], keys)


@pytest.fixture(scope="session")
def private_api_url(stack_outputs):
    return stack_outputs['PrivateApiURL']


@pytest.fixture(scope="session")
def public_api_url(stack_outputs):
    return stack_outputs['PublicApiURL']


@pytest.fixture(scope="session")
def private_api_settings(private_url, private_key):
    url = f'{private_url}/status'
    headers = {
        'x-api-key': private_key
    }
    logger.debug(f'Sending request to {url}')
    response = requests.get(url, headers=headers)
    assert response.status_code == 200
    status = response.json()
    assert 'Invalid' not in status['message']
    assert status['config']
    logger.debug(f'status: {pformat(status)}')
    return {'settings': status['config']}


@pytest.fixture(scope="session")
def appsync_api_url(stack_outputs):
    return stack_outputs['AppSyncURL']


@pytest.fixture(scope='session')
def organization_id():
    return os.environ['SMOKE_TEST_ORG_ID']
