from http import HTTPStatus
from typing import Any
from urllib.parse import quote

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.assemble_order import AssembleOrder
from ...models.cws_error_dto import CwsErrorDTO
from ...models.order import Order
from ...types import UNSET, Response, Unset


def _get_kwargs(
    customer_ekp: str,
    *,
    body: AssembleOrder,
    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/customers/{customer_ekp}/orders".format(
            customer_ekp=quote(str(customer_ekp), safe=""),
        ),
    }

    _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 | Order | None:
    if response.status_code == 200:
        response_200 = Order.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 | Order]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


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

     Creates an order from already existing items.

    Args:
        customer_ekp (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (AssembleOrder): This assembles the items or bags to a new order. EITHER bagIds OR
            itemBarcodes is REQUIRED Example: {'itemBarcodes': ['BC123456789DE', 'BC123456790DE',
            'BC123456791DE'], 'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3}}.

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

    kwargs = _get_kwargs(
        customer_ekp=customer_ekp,
        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(
    customer_ekp: str,
    *,
    client: AuthenticatedClient | Client,
    body: AssembleOrder,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> CwsErrorDTO | Order | None:
    """Create Order

     Creates an order from already existing items.

    Args:
        customer_ekp (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (AssembleOrder): This assembles the items or bags to a new order. EITHER bagIds OR
            itemBarcodes is REQUIRED Example: {'itemBarcodes': ['BC123456789DE', 'BC123456790DE',
            'BC123456791DE'], 'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3}}.

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

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


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

     Creates an order from already existing items.

    Args:
        customer_ekp (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (AssembleOrder): This assembles the items or bags to a new order. EITHER bagIds OR
            itemBarcodes is REQUIRED Example: {'itemBarcodes': ['BC123456789DE', 'BC123456790DE',
            'BC123456791DE'], 'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3}}.

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

    kwargs = _get_kwargs(
        customer_ekp=customer_ekp,
        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(
    customer_ekp: str,
    *,
    client: AuthenticatedClient | Client,
    body: AssembleOrder,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    third_party_vendor_id: str | Unset = UNSET,
) -> CwsErrorDTO | Order | None:
    """Create Order

     Creates an order from already existing items.

    Args:
        customer_ekp (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        third_party_vendor_id (str | Unset):
        body (AssembleOrder): This assembles the items or bags to a new order. EITHER bagIds OR
            itemBarcodes is REQUIRED Example: {'itemBarcodes': ['BC123456789DE', 'BC123456790DE',
            'BC123456791DE'], 'paperwork': {'contactName': 'John Doe', 'awbCopyCount': 3}}.

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

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