from __future__ import annotations

from typing import Any


class EbayClientError(Exception):
    pass


class OAuthError(EbayClientError):
    pass


class TransportError(EbayClientError):
    pass


class ResponseDecodingError(TransportError):
    pass


class ApiError(TransportError):
    def __init__(
        self,
        *,
        status_code: int,
        message: str,
        errors: list[dict[str, Any]] | None = None,
        response_body: Any | None = None,
    ) -> None:
        super().__init__(f"HTTP {status_code}: {message}")
        self.status_code = status_code
        self.message = message
        self.errors = errors or []
        self.response_body = response_body


def build_api_error(status_code: int, payload: Any) -> ApiError:
    if isinstance(payload, dict):
        errors = payload.get("errors")
        if isinstance(errors, list) and errors:
            first = errors[0]
            message = str(first.get("message") or first.get("longMessage") or "eBay API request failed")
            normalized_errors = [item for item in errors if isinstance(item, dict)]
            return ApiError(
                status_code=status_code,
                message=message,
                errors=normalized_errors,
                response_body=payload,
            )
    return ApiError(status_code=status_code, message="eBay API request failed", response_body=payload)
