import pytest
from clarabot_nano_common.common.solr.rest import create_solr_core_url, create_solr_auth_header

from clarabot_nano_tests.testing.core.instance import CoreTestingNanoInstanceHandler
from clarabot_nano_tests.testing.solr import wait_solr_startup


@pytest.mark.asyncio
async def test_core_solr_auth(reset_user_app_dirs, dev_nano_root_dir):
    async with CoreTestingNanoInstanceHandler(reset_user_app_dirs, dev_nano_root_dir).run() as (
        pm,
        session,
        children_spawns,
        dbg_config,
    ):
        solr_port = dbg_config["state"]["solr_port"]
        auth_h = create_solr_auth_header(dbg_config["state"]["solr_key"])
        assert create_solr_core_url("127.0.0.2", solr_port, "xy", "zq") == f"http://127.0.0.2:{solr_port}/solr/xy/zq"
        url = f"http://127.0.0.1:{solr_port}/solr/admin/cores?action=STATUS"

        await wait_solr_startup(session, solr_port, auth_h)

        async with session.get(url) as r:
            assert r.status == 401
        async with session.get(url, headers={"Authorization": create_solr_auth_header("password")}) as r:
            assert r.status == 401
        async with session.get(url, headers={"Authorization": auth_h}) as r:
            assert r.status == 200
