import pytest

from unittest.mock import AsyncMock

from fastapi import FastAPI
from fastapi.testclient import TestClient

from faststream.rabbit import RabbitBroker


from cattle_grid.account.account import create_account
from cattle_grid.testing.fixtures import *  # noqa
from cattle_grid.testing import mocked_broker

from . import router


@pytest.fixture(scope="session")
def test_app():
    app = FastAPI()
    app.include_router(router)
    return app


@pytest.fixture(scope="session")
def test_client(test_app):
    return TestClient(test_app)


@pytest.fixture
async def test_token(sql_session, test_client):
    account = await create_account(sql_session, "name", "pass")
    assert account
    response = test_client.post(
        "/signin", json={"name": account.name, "password": "pass"}
    )

    assert response.status_code == 200

    return response.json().get("token")


@pytest.fixture
def bearer_header(test_token):
    return {"authorization": f"Bearer {test_token}"}


@pytest.fixture(autouse=True)
def test_broker():
    my_broker = AsyncMock(RabbitBroker)
    with mocked_broker(my_broker):
        yield my_broker


@pytest.fixture
def actor_id(test_client, bearer_header):
    result = test_client.post(
        "/account/create",
        json={"baseUrl": "http://abel.test"},
        headers=bearer_header,
    )
    assert result.status_code == 201
    return result.json()["id"]
