import json
import logging

import pytest
from iqe_policies.utils.policy_utils import Policy
from pkg_resources import resource_filename

from iqe_notifications.utils.integrations_utils import Integration
from iqe_notifications.utils.notifications_utils import BehaviorGroup as BehaviorGroupUtils
from iqe_notifications.utils.notifications_utils import EventType as EventTypeUtils
from iqe_notifications.utils.webhook_site_utils import WebhookUtils

# import pytest

pytestmark = [
    pytest.mark.api,
    pytest.mark.core,
]

log = logging.getLogger("iqe")

event_file = resource_filename("iqe_notifications", "resources/data/fake_event.json")


@pytest.mark.skip(reason="Testhave to fix before run on the ibutsu")
# @pytest.mark.smoke
# TODO: uncomment the smoke marker once able to give notifications permissions on ephemeral
def test_webhook_triggered_smoke(
    application,
    rbac_init_admin_smoke_env,
    rbac_notifications_admin_smoke_setup,
    rbac_notifications_org_admin_user_username,
    new_policy,
    policy_teardown,
    integration_teardown,
    webhook_token,
    bg_teardown,
    rhel_bundle_id,
    policies_event_type_id,
):
    """
    Test webhook triggered via webhook.site on smoke env
    This test will not run on the stage env due to user does not exists.

    Polarion:
        assignee: ylahav
    """
    init_user_res = rbac_init_admin_smoke_env
    log.info(f"Init notifications admin return: {init_user_res}")
    admin = rbac_notifications_org_admin_user_username
    with application.copy_using(user=admin) as new_application:
        # set the clients
        notifications_api = new_application.notifications.rest_client_notifications.default_api
        integrations_api = new_application.notifications.rest_client_integrations.default_api

    policy_teardown(new_policy)

    # the webhooks url
    url = WebhookUtils.get_webhook_url(application, webhook_token)

    # create a new integration with the webhook url and add it to a new behavior group
    integration = Integration.create_integration_by_url(integrations_api, "test webhooks", url)
    integration_teardown(integration)
    new_bg = BehaviorGroupUtils.create_behavior_group_with_integration_id(
        notifications_api, rhel_bundle_id, "bg test webhooks", integration.id
    )
    bg_teardown(new_bg)

    EventTypeUtils.add_behavior_group_to_event_type(
        notifications_api, policies_event_type_id, new_bg.id
    )

    # trigger the policy
    Policy.trigger_policy(application, new_policy.id)

    # wait for the requests list will not be empty
    webhooks_request_list = WebhookUtils.wait_for_webhook_requests_list(application, webhook_token)

    # verify we delete the token after the test ends
    WebhookUtils.delete_token(application, webhook_token)

    # check that the content isn't empty
    assert webhooks_request_list[0]["content"], (
        f"Investigation needed: Failed to trigger webhook "
        f"or reading from webhook.site failed w/ token:{webhook_token}"
    )

    policy_found = False
    for event in json.loads(webhooks_request_list[0]["content"])["events"]:
        if event["payload"]["policy_name"] == new_policy.name:
            policy_found = True

    # check that the payload contains the name of our policy
    assert policy_found, (
        f"Policy: {new_policy.name} wasn't found in events list: "
        f"{json.loads(webhooks_request_list[0]['content'])['events']}, "
    )
