import httpx

from app.services.remnawave_client import RemnawaveApiClient


def test_normalize_base_url_adds_api_suffix() -> None:
    assert (
        RemnawaveApiClient.normalize_base_url("https://panel.example.com")
        == "https://panel.example.com/api/"
    )


def test_normalize_base_url_keeps_existing_api_suffix() -> None:
    assert (
        RemnawaveApiClient.normalize_base_url("https://panel.example.com/api/")
        == "https://panel.example.com/api/"
    )


def test_unwrap_payload_response_field() -> None:
    payload = {"response": {"ok": True}}
    assert RemnawaveApiClient.unwrap_payload(payload) == {"ok": True}


def test_build_error_includes_error_code() -> None:
    client = object.__new__(RemnawaveApiClient)
    response = httpx.Response(
        500,
        json={
            "message": "Failed to create user",
            "errorCode": "A018",
        },
        request=httpx.Request("POST", "https://panel.example.com/api/users"),
    )

    error = client._build_error(response)

    assert error.message == "Failed to create user [A018]"


def test_build_error_includes_validation_details() -> None:
    client = object.__new__(RemnawaveApiClient)
    response = httpx.Response(
        400,
        json={
            "message": "Validation failed",
            "errors": [
                {
                    "message": "Invalid uuid",
                    "path": ["uuid"],
                }
            ],
        },
        request=httpx.Request("DELETE", "https://panel.example.com/api/users/not-a-uuid"),
    )

    error = client._build_error(response)

    assert error.message == "Validation failed | uuid: Invalid uuid"
