"""
Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

Helpers mapping transfer domain errors to command ErrorResult payloads (stable §9 types).
"""

from __future__ import annotations

from mcp_proxy_adapter.api.handlers import build_transfer_error_response
from mcp_proxy_adapter.api.transfer_session_service import TransferSessionKindMismatch
from mcp_proxy_adapter.commands.result import ErrorResult
from mcp_proxy_adapter.transfer.errors import TransferError


def transfer_validation_error_result(missing_fields: list[str]) -> ErrorResult:
    """REST 422 InvalidRequest parity for payload validation failures."""
    return ErrorResult(
        message="Request validation failed",
        code=-32602,
        details={
            "error_type": "InvalidRequest",
            "missing_or_invalid_fields": missing_fields,
        },
    )


def transfer_domain_error_result(exc: TransferError) -> ErrorResult:
    """Map TransferError subclasses using the same error_type as REST HTTP JSON."""
    _status, body = build_transfer_error_response(exc)
    return ErrorResult(
        message=str(body["message"]),
        code=-32000,
        details={
            "error_type": body["error_type"],
            "message": body["message"],
            "details": body.get("details"),
        },
    )


def transfer_wrong_kind_error_result(exc: TransferSessionKindMismatch) -> ErrorResult:
    """404-style wrong-direction session (matches REST upload/download not-found bodies)."""
    if exc.expected == "upload":
        message = "Upload session not found"
    else:
        message = "Download session not found"
    return ErrorResult(
        message=message,
        code=-32000,
        details={
            "error_type": "TransferSessionNotFoundError",
            "message": message,
            "details": {"transfer_id": exc.transfer_id},
        },
    )
