"""
    Python with RabbitMQ—simplified so you won't have to.

    :copyright: 2020-Present by Alexandre Gerona.
    :license: MIT, see LICENSE for more details.

    Full documentation is available at https://pyrmq.readthedocs.io
"""
from contextlib import suppress

import pytest

from pyrmq import Publisher

TEST_EXCHANGE_NAME = "sample_exchange"
TEST_QUEUE_NAME = "test_queue_name"
TEST_ROUTING_KEY = "test_routing_key"

TEST_PRIORITY_EXCHANGE_NAME = "sample_priority_exchange"
TEST_PRIORITY_QUEUE_NAME = "sample_priority_queue_name"
TEST_PRIORITY_ROUTING_KEY = "sample_priority_routing_key"
TEST_PRIORITY_ARGUMENTS = {"x-max-priority": 5}


@pytest.fixture(scope="session")
def publisher():
    publisher = Publisher(
        exchange_name=TEST_EXCHANGE_NAME,
        queue_name=TEST_QUEUE_NAME,
        routing_key=TEST_ROUTING_KEY,
    )
    return publisher


@pytest.fixture(scope="session")
def priority_publisher():
    publisher = Publisher(
        exchange_name=TEST_PRIORITY_EXCHANGE_NAME,
        queue_name=TEST_PRIORITY_QUEUE_NAME,
        routing_key=TEST_PRIORITY_ROUTING_KEY,
        queue_args=TEST_PRIORITY_ARGUMENTS,
    )
    return publisher


@pytest.fixture(scope="function")
def publisher_session(publisher):
    # Delete queue generated by Publisher on test setup
    channel = publisher.connect()
    channel.queue_purge(TEST_QUEUE_NAME)
    with suppress(Exception):
        channel.queue_purge(f"{TEST_QUEUE_NAME}.retry")
    yield publisher
    # Delete queue generated by Publisher on test teardown
    channel = publisher.connect()
    channel.queue_purge(TEST_QUEUE_NAME)
    channel.queue_delete(TEST_QUEUE_NAME)


@pytest.fixture(scope="function")
def priority_session(priority_publisher: Publisher):
    # Delete queue generated by Publisher on test setup
    channel = priority_publisher.connect()
    channel.queue_purge(TEST_PRIORITY_QUEUE_NAME)
    yield priority_publisher
    # Delete queue generated by Publisher on test teardown
    channel = priority_publisher.connect()
    channel.queue_purge(TEST_PRIORITY_QUEUE_NAME)
    channel.queue_delete(TEST_PRIORITY_QUEUE_NAME)


@pytest.fixture(scope="function", autouse=True)
def clean_specific_queues(priority_publisher: Publisher):
    channel = priority_publisher.connect()
    channel.queue_delete("first_queue")
    channel.queue_delete("second_queue")
    channel.exchange_delete("first_exchange")
    channel.exchange_delete("second_exchange")
    channel.exchange_delete("headers_exchange_name")
