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.cws_error_dto import CwsErrorDTO
from ...models.shipment import Shipment
from ...types import Response


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

    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/dpi/shipping/v1/orders/{order_id}/shipments".format(
            order_id=quote(str(order_id), safe=""),
        ),
    }

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> CwsErrorDTO | list[Shipment] | None:
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.json()
        for response_200_item_data in _response_200:
            response_200_item = Shipment.from_dict(response_200_item_data)

            response_200.append(response_200_item)

        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 == 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 | list[Shipment]]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    order_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> Response[CwsErrorDTO | list[Shipment]]:
    """Get Shipments for an Order

     Searches shipments attached to an given order. Answers with a not found status (404) if order does
    not exist or if there are no shipmments attached to this order.

    Args:
        order_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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 | list[Shipment]]
    """

    kwargs = _get_kwargs(
        order_id=order_id,
        authorization=authorization,
    )

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

    return _build_response(client=client, response=response)


def sync(
    order_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> CwsErrorDTO | list[Shipment] | None:
    """Get Shipments for an Order

     Searches shipments attached to an given order. Answers with a not found status (404) if order does
    not exist or if there are no shipmments attached to this order.

    Args:
        order_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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 | list[Shipment]
    """

    return sync_detailed(
        order_id=order_id,
        client=client,
        authorization=authorization,
    ).parsed


async def asyncio_detailed(
    order_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> Response[CwsErrorDTO | list[Shipment]]:
    """Get Shipments for an Order

     Searches shipments attached to an given order. Answers with a not found status (404) if order does
    not exist or if there are no shipmments attached to this order.

    Args:
        order_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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 | list[Shipment]]
    """

    kwargs = _get_kwargs(
        order_id=order_id,
        authorization=authorization,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    order_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> CwsErrorDTO | list[Shipment] | None:
    """Get Shipments for an Order

     Searches shipments attached to an given order. Answers with a not found status (404) if order does
    not exist or if there are no shipmments attached to this order.

    Args:
        order_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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 | list[Shipment]
    """

    return (
        await asyncio_detailed(
            order_id=order_id,
            client=client,
            authorization=authorization,
        )
    ).parsed
