"""Pytest configuration for service portal tests.

Provides authenticated httpx clients for testing against a running server.
Set TEST_SERVER_URL env var to override the default http://localhost:8000.
"""

import os
import httpx
import pytest

SERVER_URL = os.environ.get("TEST_SERVER_URL", "http://localhost:8000")
PASSWORD = "AegisOne2024!"


def _login(role: str) -> httpx.Client:
    """Create an authenticated httpx client for the given role."""
    client = httpx.Client(base_url=SERVER_URL, follow_redirects=False, timeout=10)
    resp = client.post("/service/login", data={"login": role, "password": PASSWORD})
    assert resp.status_code == 302, f"{role} login failed: {resp.status_code} {resp.text[:200]}"
    return client


@pytest.fixture(scope="module")
def client():
    """Unauthenticated httpx client."""
    with httpx.Client(base_url=SERVER_URL, follow_redirects=False, timeout=10) as c:
        yield c


@pytest.fixture(scope="module")
def owner_client(_check_server):
    """Authenticated httpx client as owner."""
    return _login("owner")


@pytest.fixture(scope="module")
def engineer_client(_check_server):
    """Authenticated httpx client as engineer."""
    return _login("engineer")


@pytest.fixture(scope="module")
def technician_client(_check_server):
    """Authenticated httpx client as technician."""
    return _login("technician")


@pytest.fixture(scope="module")
def api_client(_check_server):
    """Authenticated httpx client as owner for API tests."""
    return _login("owner")


@pytest.fixture(scope="module")
def _check_server():
    """Sanity check — server must be reachable before running tests."""
    with httpx.Client(base_url=SERVER_URL, timeout=5) as c:
        resp = c.get("/health")
        if resp.status_code != 200:
            pytest.fail(f"Server at {SERVER_URL} is not reachable (health: {resp.status_code})")


@pytest.fixture(scope="module")
def role_client(client, owner_client, engineer_client, technician_client):
    """Dict mapping role names to authenticated httpx clients."""
    return {
        "anonymous": client,
        "owner": owner_client,
        "engineer": engineer_client,
        "technician": technician_client,
    }
