# 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 pytest

from czc import json
from czc.api.environment import TestKeyEnvironment
from czc.constants import CLOUDZERO_TEST_KEY_DO_NOT_FORWARD_SUFFIX, CLOUDZERO_TEST_KEY_EVENT_PARAMETER
from czt.unittest import MATCH, Context, MockEx

from tests.sample_data import NAMESPACE

TEST_KEY_VALUES = [None, 'test-key-value', f'test-key-value{CLOUDZERO_TEST_KEY_DO_NOT_FORWARD_SUFFIX}']
TEST_SOURCE = 'unit-test'
TEST_DETAIL_TYPE = 'Unit Test Event'


@pytest.fixture(scope='function')
def context(mocker, environ):
    from czc import event_bridge

    with Context(
        mocker,
        event_bridge,
        ['aws_service'],
        extra={
            'event_bridge': event_bridge,
        },
    ) as context:
        context.mock_aws_service.events_client.put_events.return_value = {'Entries': []}
        yield context


@pytest.mark.unit
@pytest.mark.parametrize('test_key_value', TEST_KEY_VALUES)
def test_publish_event_with_test_key(context, test_key_value):
    event = {'field1': 'value1'}

    def validate_event_detail(x):
        if x.get('field1') != 'value1':
            return False

        if test_key_value and not test_key_value.endswith(CLOUDZERO_TEST_KEY_DO_NOT_FORWARD_SUFFIX):
            return x[CLOUDZERO_TEST_KEY_EVENT_PARAMETER] == test_key_value

        return CLOUDZERO_TEST_KEY_EVENT_PARAMETER not in x

    with TestKeyEnvironment(test_key_value):
        context.event_bridge.publish_event(NAMESPACE, TEST_DETAIL_TYPE, TEST_SOURCE, event)
        assert MockEx(context.mock_aws_service.events_client.put_events).was_called_once_with(
            Entries=MATCH(
                lambda x: (
                    x[0]['Source'] == TEST_SOURCE
                    and x[0]['DetailType'] == TEST_DETAIL_TYPE
                    and x[0]['EventBusName'] == f'cz-{NAMESPACE}-events-primary'
                    and validate_event_detail(json.loads(x[0]['Detail']))
                )
            )
        )
