import pytest
from httpx import AsyncClient

pytestmark = pytest.mark.asyncio

COMPANY_URL = "/api/v1/companies/me"
DEPT_URL = "/api/v1/companies/me/departments"


def auth(tokens):
    return {"Authorization": f"Bearer {tokens['access_token']}"}


async def test_get_company(client: AsyncClient, registered_user):
    resp = await client.get(COMPANY_URL, headers=auth(registered_user["tokens"]))
    assert resp.status_code == 200
    body = resp.json()
    assert body["name"] == "Test GmbH"
    assert "slug" in body


async def test_update_company(client: AsyncClient, registered_user):
    resp = await client.patch(
        COMPANY_URL,
        headers=auth(registered_user["tokens"]),
        json={"name": "Test GmbH Updated", "state": "BY"},
    )
    assert resp.status_code == 200
    assert resp.json()["state"] == "BY"


async def test_create_department(client: AsyncClient, registered_user):
    resp = await client.post(DEPT_URL, headers=auth(registered_user["tokens"]), json={
        "name": "Engineering",
    })
    assert resp.status_code == 201
    body = resp.json()
    assert body["name"] == "Engineering"
    return body["id"]


async def test_list_departments(client: AsyncClient, registered_user):
    await client.post(DEPT_URL, headers=auth(registered_user["tokens"]), json={"name": "HR"})
    resp = await client.get(DEPT_URL, headers=auth(registered_user["tokens"]))
    assert resp.status_code == 200
    assert isinstance(resp.json(), list)
    assert len(resp.json()) >= 1


async def test_update_department(client: AsyncClient, registered_user):
    cr = await client.post(DEPT_URL, headers=auth(registered_user["tokens"]), json={"name": "Old Name"})
    dept_id = cr.json()["id"]
    resp = await client.patch(
        f"{DEPT_URL}/{dept_id}",
        headers=auth(registered_user["tokens"]),
        json={"name": "New Name"},
    )
    assert resp.status_code == 200
    assert resp.json()["name"] == "New Name"


async def test_delete_department(client: AsyncClient, registered_user):
    cr = await client.post(DEPT_URL, headers=auth(registered_user["tokens"]), json={"name": "ToDelete"})
    dept_id = cr.json()["id"]
    resp = await client.delete(f"{DEPT_URL}/{dept_id}", headers=auth(registered_user["tokens"]))
    assert resp.status_code == 204
