import pytest
from elasticsearch import Elasticsearch

from events.constants import ELK_HOST, ELK_PORT, ELK_LOGIN, ELK_PASS
from rotation.tasks import delete_elasticsearch_indexes_by_template

TEST_EXCLUDE_INDEXES = [
    ({'test-index-1'}, 1),
    ({'test-index-1', 'test-index2'}, 1),
]


class TestDeleteElasticsearchIndexes:
    # TODO: add random index name
    index_name = 'test-index'

    @pytest.fixture(autouse=True)
    def setup_tests(self):
        self.es = Elasticsearch([{'host': ELK_HOST, 'port': ELK_PORT}], http_auth=(ELK_LOGIN, ELK_PASS))
        for i in range(3):
            self.es.indices.create(index=f'{self.index_name}-{i}', ignore=400)
        yield
        self.es.indices.delete(index=f'{self.index_name}-*', ignore=[400, 404])

    @pytest.mark.integration
    def test_delete_all_index_by_template(self):
        index_template = f'{self.index_name}-*'
        index_count = len(self.es.indices.get_alias(index=index_template).keys())
        assert index_count == 3
        delete_elasticsearch_indexes_by_template(index_template)
        assert len(self.es.indices.get_alias(index=index_template)) == 0

    @pytest.mark.parametrize('exclude_indexes,expected', TEST_EXCLUDE_INDEXES)
    @pytest.mark.integration
    def test_delete_index_by_template_witch_exclude_index(self, exclude_indexes: set, expected: int):
        index_template = f'{self.index_name}-*'
        delete_elasticsearch_indexes_by_template(index_template, es=self.es, exclude_indexes=exclude_indexes)
        assert len(self.es.indices.get_alias(index=index_template, ignore=[400, 404])) == expected
