from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.cws_error_dto import CwsErrorDTO
from ...models.validation import Validation
from ...types import UNSET, Response, Unset


def _get_kwargs(
    *,
    body: Validation,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    headers["Authorization"] = authorization

    if not isinstance(third_party_vendor_id, Unset):
        headers["ThirdPartyVendor-ID"] = third_party_vendor_id

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/dpi/shipping/v1/validation",
    }

    _kwargs["json"] = body.to_dict()

    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> CwsErrorDTO | Validation | None:
    if response.status_code == 200:
        response_200 = Validation.from_dict(response.json())

        return response_200

    if response.status_code == 400:
        response_400 = CwsErrorDTO.from_dict(response.json())

        return response_400

    if response.status_code == 401:
        response_401 = CwsErrorDTO.from_dict(response.json())

        return response_401

    if response.status_code == 406:
        response_406 = CwsErrorDTO.from_dict(response.json())

        return response_406

    if response.status_code == 422:
        response_422 = CwsErrorDTO.from_dict(response.json())

        return response_422

    if response.status_code == 500:
        response_500 = CwsErrorDTO.from_dict(response.json())

        return response_500

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


def _build_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[CwsErrorDTO | Validation]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: Validation,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> Response[CwsErrorDTO | Validation]:
    """Validate Order Items

     Validate OrderItems, required by efiliale

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (Validation):  Example: {'customerEkp': '9012345678', 'items': [{'product': 'GMP',
            'serviceLevel': 'PRIORITY', 'custRef': '02 03 02 02 T005', 'recipient': 'Herschel
            Krustofsky', 'recipientPhone': '', 'recipientFax': '', 'recipientEmail': '',
            'addressLine1': 'Avenue des Champs-Élysées', 'addressLine2': '', 'addressLine3': '103',
            'city': 'Paris', 'state': 'Île-de-France', 'postalCode': '75020', 'destinationCountry':
            'FR', 'returnItemWanted': False, 'shipmentAmount': 0, 'shipmentCurrency': 'EUR',
            'shipmentGrossWeight': 500}]}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[CwsErrorDTO | Validation]
    """

    kwargs = _get_kwargs(
        body=body,
        authorization=authorization,
        third_party_vendor_id=third_party_vendor_id,
    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)


def sync(
    *,
    client: AuthenticatedClient | Client,
    body: Validation,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> CwsErrorDTO | Validation | None:
    """Validate Order Items

     Validate OrderItems, required by efiliale

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (Validation):  Example: {'customerEkp': '9012345678', 'items': [{'product': 'GMP',
            'serviceLevel': 'PRIORITY', 'custRef': '02 03 02 02 T005', 'recipient': 'Herschel
            Krustofsky', 'recipientPhone': '', 'recipientFax': '', 'recipientEmail': '',
            'addressLine1': 'Avenue des Champs-Élysées', 'addressLine2': '', 'addressLine3': '103',
            'city': 'Paris', 'state': 'Île-de-France', 'postalCode': '75020', 'destinationCountry':
            'FR', 'returnItemWanted': False, 'shipmentAmount': 0, 'shipmentCurrency': 'EUR',
            'shipmentGrossWeight': 500}]}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        CwsErrorDTO | Validation
    """

    return sync_detailed(
        client=client,
        body=body,
        authorization=authorization,
        third_party_vendor_id=third_party_vendor_id,
    ).parsed


async def asyncio_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: Validation,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> Response[CwsErrorDTO | Validation]:
    """Validate Order Items

     Validate OrderItems, required by efiliale

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (Validation):  Example: {'customerEkp': '9012345678', 'items': [{'product': 'GMP',
            'serviceLevel': 'PRIORITY', 'custRef': '02 03 02 02 T005', 'recipient': 'Herschel
            Krustofsky', 'recipientPhone': '', 'recipientFax': '', 'recipientEmail': '',
            'addressLine1': 'Avenue des Champs-Élysées', 'addressLine2': '', 'addressLine3': '103',
            'city': 'Paris', 'state': 'Île-de-France', 'postalCode': '75020', 'destinationCountry':
            'FR', 'returnItemWanted': False, 'shipmentAmount': 0, 'shipmentCurrency': 'EUR',
            'shipmentGrossWeight': 500}]}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[CwsErrorDTO | Validation]
    """

    kwargs = _get_kwargs(
        body=body,
        authorization=authorization,
        third_party_vendor_id=third_party_vendor_id,
    )

    response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(client=client, response=response)


async def asyncio(
    *,
    client: AuthenticatedClient | Client,
    body: Validation,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> CwsErrorDTO | Validation | None:
    """Validate Order Items

     Validate OrderItems, required by efiliale

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (Validation):  Example: {'customerEkp': '9012345678', 'items': [{'product': 'GMP',
            'serviceLevel': 'PRIORITY', 'custRef': '02 03 02 02 T005', 'recipient': 'Herschel
            Krustofsky', 'recipientPhone': '', 'recipientFax': '', 'recipientEmail': '',
            'addressLine1': 'Avenue des Champs-Élysées', 'addressLine2': '', 'addressLine3': '103',
            'city': 'Paris', 'state': 'Île-de-France', 'postalCode': '75020', 'destinationCountry':
            'FR', 'returnItemWanted': False, 'shipmentAmount': 0, 'shipmentCurrency': 'EUR',
            'shipmentGrossWeight': 500}]}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        CwsErrorDTO | Validation
    """

    return (
        await asyncio_detailed(
            client=client,
            body=body,
            authorization=authorization,
            third_party_vendor_id=third_party_vendor_id,
        )
    ).parsed
