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.order_data import OrderData
from ...models.order_response import OrderResponse
from ...types import UNSET, Response, Unset


def _get_kwargs(
    *,
    body: OrderData,
    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/orders",
    }

    _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 | OrderResponse | None:
    if response.status_code == 200:
        response_200 = OrderResponse.from_dict(response.json())

        return response_200

    if response.status_code == 403:
        response_403 = CwsErrorDTO.from_dict(response.json())

        return response_403

    if response.status_code == 404:
        response_404 = CwsErrorDTO.from_dict(response.json())

        return response_404

    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 | OrderResponse]:
    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: OrderData,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> Response[CwsErrorDTO | OrderResponse]:
    """Create Order

     Creates a new order based on the given JSON data

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (OrderData):  Example: {'customerEkp': '9012345678', 'orderStatus': 'FINALIZE',
            'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3, 'jobReference': 'Job ref',
            'pickupType': 'CUSTOMER_DROP_OFF', 'telephoneNumber': '+4935120681234'}, 'items':
            [{'product': 'GMP', 'serviceLevel': 'PRIORITY', 'recipient': 'John Doe', 'addressLine1':
            'Any Street', 'addressLine2': 'Flat 2', 'addressLine3': '1st floor', 'postalCode':
            '01432', 'city': 'Any City', 'state': 'Any State', 'destinationCountry': 'DE', 'custRef':
            'REF-2361890-AB', 'recipientPhone': '+44123456789', 'recipientFax': '+44123456789',
            'recipientEmail': 'john.doe@example.eu', 'senderTaxId': 'IOSS number', 'importerTaxId':
            'IOSS number', 'shipmentAmount': 100, 'shipmentCurrency': 'EUR', 'shipmentGrossWeight':
            1500, 'returnItemWanted': False, 'shipmentNaturetype': 'SALE_GOODS', 'contents':
            [{'contentPieceHsCode': 1234567890, 'contentPieceDescription': 'Trousers',
            'contentPieceValue': '120.50', 'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE',
            'contentPieceAmount': 2}]}]}.

    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 | OrderResponse]
    """

    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: OrderData,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> CwsErrorDTO | OrderResponse | None:
    """Create Order

     Creates a new order based on the given JSON data

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (OrderData):  Example: {'customerEkp': '9012345678', 'orderStatus': 'FINALIZE',
            'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3, 'jobReference': 'Job ref',
            'pickupType': 'CUSTOMER_DROP_OFF', 'telephoneNumber': '+4935120681234'}, 'items':
            [{'product': 'GMP', 'serviceLevel': 'PRIORITY', 'recipient': 'John Doe', 'addressLine1':
            'Any Street', 'addressLine2': 'Flat 2', 'addressLine3': '1st floor', 'postalCode':
            '01432', 'city': 'Any City', 'state': 'Any State', 'destinationCountry': 'DE', 'custRef':
            'REF-2361890-AB', 'recipientPhone': '+44123456789', 'recipientFax': '+44123456789',
            'recipientEmail': 'john.doe@example.eu', 'senderTaxId': 'IOSS number', 'importerTaxId':
            'IOSS number', 'shipmentAmount': 100, 'shipmentCurrency': 'EUR', 'shipmentGrossWeight':
            1500, 'returnItemWanted': False, 'shipmentNaturetype': 'SALE_GOODS', 'contents':
            [{'contentPieceHsCode': 1234567890, 'contentPieceDescription': 'Trousers',
            'contentPieceValue': '120.50', 'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE',
            'contentPieceAmount': 2}]}]}.

    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 | OrderResponse
    """

    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: OrderData,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> Response[CwsErrorDTO | OrderResponse]:
    """Create Order

     Creates a new order based on the given JSON data

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (OrderData):  Example: {'customerEkp': '9012345678', 'orderStatus': 'FINALIZE',
            'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3, 'jobReference': 'Job ref',
            'pickupType': 'CUSTOMER_DROP_OFF', 'telephoneNumber': '+4935120681234'}, 'items':
            [{'product': 'GMP', 'serviceLevel': 'PRIORITY', 'recipient': 'John Doe', 'addressLine1':
            'Any Street', 'addressLine2': 'Flat 2', 'addressLine3': '1st floor', 'postalCode':
            '01432', 'city': 'Any City', 'state': 'Any State', 'destinationCountry': 'DE', 'custRef':
            'REF-2361890-AB', 'recipientPhone': '+44123456789', 'recipientFax': '+44123456789',
            'recipientEmail': 'john.doe@example.eu', 'senderTaxId': 'IOSS number', 'importerTaxId':
            'IOSS number', 'shipmentAmount': 100, 'shipmentCurrency': 'EUR', 'shipmentGrossWeight':
            1500, 'returnItemWanted': False, 'shipmentNaturetype': 'SALE_GOODS', 'contents':
            [{'contentPieceHsCode': 1234567890, 'contentPieceDescription': 'Trousers',
            'contentPieceValue': '120.50', 'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE',
            'contentPieceAmount': 2}]}]}.

    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 | OrderResponse]
    """

    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: OrderData,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> CwsErrorDTO | OrderResponse | None:
    """Create Order

     Creates a new order based on the given JSON data

    Args:
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (OrderData):  Example: {'customerEkp': '9012345678', 'orderStatus': 'FINALIZE',
            'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3, 'jobReference': 'Job ref',
            'pickupType': 'CUSTOMER_DROP_OFF', 'telephoneNumber': '+4935120681234'}, 'items':
            [{'product': 'GMP', 'serviceLevel': 'PRIORITY', 'recipient': 'John Doe', 'addressLine1':
            'Any Street', 'addressLine2': 'Flat 2', 'addressLine3': '1st floor', 'postalCode':
            '01432', 'city': 'Any City', 'state': 'Any State', 'destinationCountry': 'DE', 'custRef':
            'REF-2361890-AB', 'recipientPhone': '+44123456789', 'recipientFax': '+44123456789',
            'recipientEmail': 'john.doe@example.eu', 'senderTaxId': 'IOSS number', 'importerTaxId':
            'IOSS number', 'shipmentAmount': 100, 'shipmentCurrency': 'EUR', 'shipmentGrossWeight':
            1500, 'returnItemWanted': False, 'shipmentNaturetype': 'SALE_GOODS', 'contents':
            [{'contentPieceHsCode': 1234567890, 'contentPieceDescription': 'Trousers',
            'contentPieceValue': '120.50', 'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE',
            'contentPieceAmount': 2}]}]}.

    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 | OrderResponse
    """

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