<?php
/**
 * DepartmentsApi
 * PHP version 8.1
 *
 * @category Class
 * @package  Opsuite2
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * OpSuite API
 *
 * <p>Welcome the the OpSuite.API.  This swagger page is the best place to familiarize yourself with the API before you write any client code.  </p<p>Here is some general information about the use of the API.<p><p><b>Authentication</b><p>All requests require authentication. You will need a username and password in order to obtain a bearer token that is then used with all requests. If you do not have a username and password then contact the enterprise you are developing for.</p><p><b>Rate Limits</b><p><p>OpSuite.API is limited on a per client basis.<p><p>In order for your client to be allocated the correct rate limits you should add a header to your request with a Key of X-ClientId and a Value of your username.<p><p>You should then contact us so we can setup your rate limits.<p><p>If you do not set the X-ClientId header then your requests will be limited by a default set of low rates limits.<p><p>It is important that you use the API in the most efficient way so that you do not reach the rate limits.<p><p>Requests exceeding the limit will return a '429 Too Many Requests' along with a JSON error message.<p><p>A client's limits and usage are reported with every API request as part of the HTTP Headers.<p><p>Example successful response headers:<p><p>HTTP/1.1 200 OK<br>X-Rate-Limit: 24h<br>X-Rate-Limit-Remaining: 249963<br>X-Rate-Limit-Reset: 2022-11-25T09:20:41<p><p>Example rate-limited response JSON error message and headers:<p><p>Content: API calls quota exceeded! maximum admitted 4500 per 15m.<br>HTTP/1.1 429 Too many Requests<br>Retry-After: 10 (seconds)<p>
 *
 * The version of the OpenAPI document: v2
 * Contact: opsuitesupport@davrich.co.uk
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.13.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace Opsuite2\Api;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Opsuite2\ApiException;
use Opsuite2\Configuration;
use Opsuite2\FormDataProcessor;
use Opsuite2\HeaderSelector;
use Opsuite2\ObjectSerializer;

/**
 * DepartmentsApi Class Doc Comment
 *
 * @category Class
 * @package  Opsuite2
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class DepartmentsApi
{
    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @var HeaderSelector
     */
    protected $headerSelector;

    /**
     * @var int Host index
     */
    protected $hostIndex;

    /** @var string[] $contentTypes **/
    public const contentTypes = [
        'apiV1DepartmentsDepartmentIdPatch' => [
            'application/json',
            'text/json',
            'application/*+json',
        ],
        'apiV1DepartmentsGet' => [
            'application/json',
        ],
        'apiV1DepartmentsGetDepartmentByCodeGet' => [
            'application/json',
        ],
        'apiV1DepartmentsPatchMultipleDepartmentsPatch' => [
            'application/json',
            'text/json',
            'application/*+json',
        ],
        'apiV1DepartmentsPost' => [
            'application/json',
            'text/json',
            'application/*+json',
        ],
        'apiV1DepartmentsPostMultipleDepartmentsPost' => [
            'application/json',
            'text/json',
            'application/*+json',
        ],
        'getDepartmentById' => [
            'application/json',
        ],
    ];

    /**
     * @param ClientInterface $client
     * @param Configuration   $config
     * @param HeaderSelector  $selector
     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        ?ClientInterface $client = null,
        ?Configuration $config = null,
        ?HeaderSelector $selector = null,
        int $hostIndex = 0
    ) {
        $this->client = $client ?: new Client();
        $this->config = $config ?: Configuration::getDefaultConfiguration();
        $this->headerSelector = $selector ?: new HeaderSelector();
        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex($hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index
     *
     * @return int Host index
     */
    public function getHostIndex()
    {
        return $this->hostIndex;
    }

    /**
     * @return Configuration
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Operation apiV1DepartmentsDepartmentIdPatch
     *
     * Updates specified properties of a department.
     *
     * @param  int $department_id department_id (required)
     * @param  \Opsuite2\Model\Patch[]|null $patch patch (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsDepartmentIdPatch'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return void
     */
    public function apiV1DepartmentsDepartmentIdPatch($department_id, $patch = null, string $contentType = self::contentTypes['apiV1DepartmentsDepartmentIdPatch'][0])
    {
        $this->apiV1DepartmentsDepartmentIdPatchWithHttpInfo($department_id, $patch, $contentType);
    }

    /**
     * Operation apiV1DepartmentsDepartmentIdPatchWithHttpInfo
     *
     * Updates specified properties of a department.
     *
     * @param  int $department_id (required)
     * @param  \Opsuite2\Model\Patch[]|null $patch (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsDepartmentIdPatch'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function apiV1DepartmentsDepartmentIdPatchWithHttpInfo($department_id, $patch = null, string $contentType = self::contentTypes['apiV1DepartmentsDepartmentIdPatch'][0])
    {
        $request = $this->apiV1DepartmentsDepartmentIdPatchRequest($department_id, $patch, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation apiV1DepartmentsDepartmentIdPatchAsync
     *
     * Updates specified properties of a department.
     *
     * @param  int $department_id (required)
     * @param  \Opsuite2\Model\Patch[]|null $patch (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsDepartmentIdPatch'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsDepartmentIdPatchAsync($department_id, $patch = null, string $contentType = self::contentTypes['apiV1DepartmentsDepartmentIdPatch'][0])
    {
        return $this->apiV1DepartmentsDepartmentIdPatchAsyncWithHttpInfo($department_id, $patch, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation apiV1DepartmentsDepartmentIdPatchAsyncWithHttpInfo
     *
     * Updates specified properties of a department.
     *
     * @param  int $department_id (required)
     * @param  \Opsuite2\Model\Patch[]|null $patch (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsDepartmentIdPatch'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsDepartmentIdPatchAsyncWithHttpInfo($department_id, $patch = null, string $contentType = self::contentTypes['apiV1DepartmentsDepartmentIdPatch'][0])
    {
        $returnType = '';
        $request = $this->apiV1DepartmentsDepartmentIdPatchRequest($department_id, $patch, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'apiV1DepartmentsDepartmentIdPatch'
     *
     * @param  int $department_id (required)
     * @param  \Opsuite2\Model\Patch[]|null $patch (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsDepartmentIdPatch'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function apiV1DepartmentsDepartmentIdPatchRequest($department_id, $patch = null, string $contentType = self::contentTypes['apiV1DepartmentsDepartmentIdPatch'][0])
    {

        // verify the required parameter 'department_id' is set
        if ($department_id === null || (is_array($department_id) && count($department_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $department_id when calling apiV1DepartmentsDepartmentIdPatch'
            );
        }
        if ($department_id < 1) {
            throw new \InvalidArgumentException('invalid value for "$department_id" when calling DepartmentsApi.apiV1DepartmentsDepartmentIdPatch, must be bigger than or equal to 1.');
        }
        


        $resourcePath = '/api/v1/Departments/{departmentId}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($department_id !== null) {
            $resourcePath = str_replace(
                '{' . 'departmentId' . '}',
                ObjectSerializer::toPathValue($department_id),
                $resourcePath
            );
        }


        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($patch)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($patch));
            } else {
                $httpBody = $patch;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'PATCH',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation apiV1DepartmentsGet
     *
     * Returns an array of Departments that match the specified search criteria.
     *
     * @param  int|null $page_number page_number (optional)
     * @param  int|null $page_size page_size (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGet'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Opsuite2\Model\Department[]|string
     */
    public function apiV1DepartmentsGet($page_number = null, $page_size = null, string $contentType = self::contentTypes['apiV1DepartmentsGet'][0])
    {
        list($response) = $this->apiV1DepartmentsGetWithHttpInfo($page_number, $page_size, $contentType);
        return $response;
    }

    /**
     * Operation apiV1DepartmentsGetWithHttpInfo
     *
     * Returns an array of Departments that match the specified search criteria.
     *
     * @param  int|null $page_number (optional)
     * @param  int|null $page_size (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGet'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Opsuite2\Model\Department[]|string, HTTP status code, HTTP response headers (array of strings)
     */
    public function apiV1DepartmentsGetWithHttpInfo($page_number = null, $page_size = null, string $contentType = self::contentTypes['apiV1DepartmentsGet'][0])
    {
        $request = $this->apiV1DepartmentsGetRequest($page_number, $page_size, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Opsuite2\Model\Department[]',
                        $request,
                        $response,
                    );
                case 400:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
            }

            

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Opsuite2\Model\Department[]',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Opsuite2\Model\Department[]',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation apiV1DepartmentsGetAsync
     *
     * Returns an array of Departments that match the specified search criteria.
     *
     * @param  int|null $page_number (optional)
     * @param  int|null $page_size (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGet'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsGetAsync($page_number = null, $page_size = null, string $contentType = self::contentTypes['apiV1DepartmentsGet'][0])
    {
        return $this->apiV1DepartmentsGetAsyncWithHttpInfo($page_number, $page_size, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation apiV1DepartmentsGetAsyncWithHttpInfo
     *
     * Returns an array of Departments that match the specified search criteria.
     *
     * @param  int|null $page_number (optional)
     * @param  int|null $page_size (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGet'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsGetAsyncWithHttpInfo($page_number = null, $page_size = null, string $contentType = self::contentTypes['apiV1DepartmentsGet'][0])
    {
        $returnType = '\Opsuite2\Model\Department[]';
        $request = $this->apiV1DepartmentsGetRequest($page_number, $page_size, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'apiV1DepartmentsGet'
     *
     * @param  int|null $page_number (optional)
     * @param  int|null $page_size (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGet'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function apiV1DepartmentsGetRequest($page_number = null, $page_size = null, string $contentType = self::contentTypes['apiV1DepartmentsGet'][0])
    {




        $resourcePath = '/api/v1/Departments';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page_number,
            'PageNumber', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page_size,
            'PageSize', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);




        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation apiV1DepartmentsGetDepartmentByCodeGet
     *
     * Returns a single Department with the specified code.
     *
     * @param  string|null $department_code department_code (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Opsuite2\Model\Department|string
     */
    public function apiV1DepartmentsGetDepartmentByCodeGet($department_code = null, string $contentType = self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'][0])
    {
        list($response) = $this->apiV1DepartmentsGetDepartmentByCodeGetWithHttpInfo($department_code, $contentType);
        return $response;
    }

    /**
     * Operation apiV1DepartmentsGetDepartmentByCodeGetWithHttpInfo
     *
     * Returns a single Department with the specified code.
     *
     * @param  string|null $department_code (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Opsuite2\Model\Department|string, HTTP status code, HTTP response headers (array of strings)
     */
    public function apiV1DepartmentsGetDepartmentByCodeGetWithHttpInfo($department_code = null, string $contentType = self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'][0])
    {
        $request = $this->apiV1DepartmentsGetDepartmentByCodeGetRequest($department_code, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Opsuite2\Model\Department',
                        $request,
                        $response,
                    );
                case 400:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
            }

            

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Opsuite2\Model\Department',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Opsuite2\Model\Department',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation apiV1DepartmentsGetDepartmentByCodeGetAsync
     *
     * Returns a single Department with the specified code.
     *
     * @param  string|null $department_code (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsGetDepartmentByCodeGetAsync($department_code = null, string $contentType = self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'][0])
    {
        return $this->apiV1DepartmentsGetDepartmentByCodeGetAsyncWithHttpInfo($department_code, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation apiV1DepartmentsGetDepartmentByCodeGetAsyncWithHttpInfo
     *
     * Returns a single Department with the specified code.
     *
     * @param  string|null $department_code (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsGetDepartmentByCodeGetAsyncWithHttpInfo($department_code = null, string $contentType = self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'][0])
    {
        $returnType = '\Opsuite2\Model\Department';
        $request = $this->apiV1DepartmentsGetDepartmentByCodeGetRequest($department_code, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'apiV1DepartmentsGetDepartmentByCodeGet'
     *
     * @param  string|null $department_code (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function apiV1DepartmentsGetDepartmentByCodeGetRequest($department_code = null, string $contentType = self::contentTypes['apiV1DepartmentsGetDepartmentByCodeGet'][0])
    {



        $resourcePath = '/api/v1/Departments/GetDepartmentByCode';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $department_code,
            'departmentCode', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);




        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation apiV1DepartmentsPatchMultipleDepartmentsPatch
     *
     * Updates specified properties of multiple departments.
     *
     * @param  \Opsuite2\Model\PatchCollection[]|null $patch_collection patch_collection (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Opsuite2\Model\PatchResponse[]|string
     */
    public function apiV1DepartmentsPatchMultipleDepartmentsPatch($patch_collection = null, string $contentType = self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'][0])
    {
        list($response) = $this->apiV1DepartmentsPatchMultipleDepartmentsPatchWithHttpInfo($patch_collection, $contentType);
        return $response;
    }

    /**
     * Operation apiV1DepartmentsPatchMultipleDepartmentsPatchWithHttpInfo
     *
     * Updates specified properties of multiple departments.
     *
     * @param  \Opsuite2\Model\PatchCollection[]|null $patch_collection (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Opsuite2\Model\PatchResponse[]|string, HTTP status code, HTTP response headers (array of strings)
     */
    public function apiV1DepartmentsPatchMultipleDepartmentsPatchWithHttpInfo($patch_collection = null, string $contentType = self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'][0])
    {
        $request = $this->apiV1DepartmentsPatchMultipleDepartmentsPatchRequest($patch_collection, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 202:
                    return $this->handleResponseWithDataType(
                        '\Opsuite2\Model\PatchResponse[]',
                        $request,
                        $response,
                    );
                case 400:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
            }

            

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Opsuite2\Model\PatchResponse[]',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 202:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Opsuite2\Model\PatchResponse[]',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation apiV1DepartmentsPatchMultipleDepartmentsPatchAsync
     *
     * Updates specified properties of multiple departments.
     *
     * @param  \Opsuite2\Model\PatchCollection[]|null $patch_collection (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsPatchMultipleDepartmentsPatchAsync($patch_collection = null, string $contentType = self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'][0])
    {
        return $this->apiV1DepartmentsPatchMultipleDepartmentsPatchAsyncWithHttpInfo($patch_collection, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation apiV1DepartmentsPatchMultipleDepartmentsPatchAsyncWithHttpInfo
     *
     * Updates specified properties of multiple departments.
     *
     * @param  \Opsuite2\Model\PatchCollection[]|null $patch_collection (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsPatchMultipleDepartmentsPatchAsyncWithHttpInfo($patch_collection = null, string $contentType = self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'][0])
    {
        $returnType = '\Opsuite2\Model\PatchResponse[]';
        $request = $this->apiV1DepartmentsPatchMultipleDepartmentsPatchRequest($patch_collection, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'apiV1DepartmentsPatchMultipleDepartmentsPatch'
     *
     * @param  \Opsuite2\Model\PatchCollection[]|null $patch_collection (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function apiV1DepartmentsPatchMultipleDepartmentsPatchRequest($patch_collection = null, string $contentType = self::contentTypes['apiV1DepartmentsPatchMultipleDepartmentsPatch'][0])
    {



        $resourcePath = '/api/v1/Departments/PatchMultipleDepartments';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($patch_collection)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($patch_collection));
            } else {
                $httpBody = $patch_collection;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'PATCH',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation apiV1DepartmentsPost
     *
     * Creates a new department.
     *
     * @param  \Opsuite2\Model\Department|null $department department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPost'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Opsuite2\Model\Department|string|string
     */
    public function apiV1DepartmentsPost($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPost'][0])
    {
        list($response) = $this->apiV1DepartmentsPostWithHttpInfo($department, $contentType);
        return $response;
    }

    /**
     * Operation apiV1DepartmentsPostWithHttpInfo
     *
     * Creates a new department.
     *
     * @param  \Opsuite2\Model\Department|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPost'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Opsuite2\Model\Department|string|string, HTTP status code, HTTP response headers (array of strings)
     */
    public function apiV1DepartmentsPostWithHttpInfo($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPost'][0])
    {
        $request = $this->apiV1DepartmentsPostRequest($department, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 201:
                    return $this->handleResponseWithDataType(
                        '\Opsuite2\Model\Department',
                        $request,
                        $response,
                    );
                case 422:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
                case 400:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
            }

            

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Opsuite2\Model\Department',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Opsuite2\Model\Department',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 422:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation apiV1DepartmentsPostAsync
     *
     * Creates a new department.
     *
     * @param  \Opsuite2\Model\Department|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPost'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsPostAsync($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPost'][0])
    {
        return $this->apiV1DepartmentsPostAsyncWithHttpInfo($department, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation apiV1DepartmentsPostAsyncWithHttpInfo
     *
     * Creates a new department.
     *
     * @param  \Opsuite2\Model\Department|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPost'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsPostAsyncWithHttpInfo($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPost'][0])
    {
        $returnType = '\Opsuite2\Model\Department';
        $request = $this->apiV1DepartmentsPostRequest($department, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'apiV1DepartmentsPost'
     *
     * @param  \Opsuite2\Model\Department|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPost'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function apiV1DepartmentsPostRequest($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPost'][0])
    {



        $resourcePath = '/api/v1/Departments';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($department)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($department));
            } else {
                $httpBody = $department;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'POST',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation apiV1DepartmentsPostMultipleDepartmentsPost
     *
     * Creates multiple new departments.
     *
     * @param  \Opsuite2\Model\Department[]|null $department department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Opsuite2\Model\PostResponseDepartment[]|string
     */
    public function apiV1DepartmentsPostMultipleDepartmentsPost($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'][0])
    {
        list($response) = $this->apiV1DepartmentsPostMultipleDepartmentsPostWithHttpInfo($department, $contentType);
        return $response;
    }

    /**
     * Operation apiV1DepartmentsPostMultipleDepartmentsPostWithHttpInfo
     *
     * Creates multiple new departments.
     *
     * @param  \Opsuite2\Model\Department[]|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Opsuite2\Model\PostResponseDepartment[]|string, HTTP status code, HTTP response headers (array of strings)
     */
    public function apiV1DepartmentsPostMultipleDepartmentsPostWithHttpInfo($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'][0])
    {
        $request = $this->apiV1DepartmentsPostMultipleDepartmentsPostRequest($department, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 201:
                    return $this->handleResponseWithDataType(
                        '\Opsuite2\Model\PostResponseDepartment[]',
                        $request,
                        $response,
                    );
                case 400:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
            }

            

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Opsuite2\Model\PostResponseDepartment[]',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Opsuite2\Model\PostResponseDepartment[]',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation apiV1DepartmentsPostMultipleDepartmentsPostAsync
     *
     * Creates multiple new departments.
     *
     * @param  \Opsuite2\Model\Department[]|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsPostMultipleDepartmentsPostAsync($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'][0])
    {
        return $this->apiV1DepartmentsPostMultipleDepartmentsPostAsyncWithHttpInfo($department, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation apiV1DepartmentsPostMultipleDepartmentsPostAsyncWithHttpInfo
     *
     * Creates multiple new departments.
     *
     * @param  \Opsuite2\Model\Department[]|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function apiV1DepartmentsPostMultipleDepartmentsPostAsyncWithHttpInfo($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'][0])
    {
        $returnType = '\Opsuite2\Model\PostResponseDepartment[]';
        $request = $this->apiV1DepartmentsPostMultipleDepartmentsPostRequest($department, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'apiV1DepartmentsPostMultipleDepartmentsPost'
     *
     * @param  \Opsuite2\Model\Department[]|null $department (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function apiV1DepartmentsPostMultipleDepartmentsPostRequest($department = null, string $contentType = self::contentTypes['apiV1DepartmentsPostMultipleDepartmentsPost'][0])
    {



        $resourcePath = '/api/v1/Departments/PostMultipleDepartments';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($department)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($department));
            } else {
                $httpBody = $department;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'POST',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getDepartmentById
     *
     * Returns a single Department with the specified id.
     *
     * @param  int $department_id department_id (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getDepartmentById'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Opsuite2\Model\Department|string
     */
    public function getDepartmentById($department_id, string $contentType = self::contentTypes['getDepartmentById'][0])
    {
        list($response) = $this->getDepartmentByIdWithHttpInfo($department_id, $contentType);
        return $response;
    }

    /**
     * Operation getDepartmentByIdWithHttpInfo
     *
     * Returns a single Department with the specified id.
     *
     * @param  int $department_id (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getDepartmentById'] to see the possible values for this operation
     *
     * @throws \Opsuite2\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Opsuite2\Model\Department|string, HTTP status code, HTTP response headers (array of strings)
     */
    public function getDepartmentByIdWithHttpInfo($department_id, string $contentType = self::contentTypes['getDepartmentById'][0])
    {
        $request = $this->getDepartmentByIdRequest($department_id, $contentType);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Opsuite2\Model\Department',
                        $request,
                        $response,
                    );
                case 400:
                    return $this->handleResponseWithDataType(
                        'string',
                        $request,
                        $response,
                    );
            }

            

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Opsuite2\Model\Department',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Opsuite2\Model\Department',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                case 400:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'string',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation getDepartmentByIdAsync
     *
     * Returns a single Department with the specified id.
     *
     * @param  int $department_id (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getDepartmentById'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getDepartmentByIdAsync($department_id, string $contentType = self::contentTypes['getDepartmentById'][0])
    {
        return $this->getDepartmentByIdAsyncWithHttpInfo($department_id, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getDepartmentByIdAsyncWithHttpInfo
     *
     * Returns a single Department with the specified id.
     *
     * @param  int $department_id (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getDepartmentById'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getDepartmentByIdAsyncWithHttpInfo($department_id, string $contentType = self::contentTypes['getDepartmentById'][0])
    {
        $returnType = '\Opsuite2\Model\Department';
        $request = $this->getDepartmentByIdRequest($department_id, $contentType);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'getDepartmentById'
     *
     * @param  int $department_id (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getDepartmentById'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getDepartmentByIdRequest($department_id, string $contentType = self::contentTypes['getDepartmentById'][0])
    {

        // verify the required parameter 'department_id' is set
        if ($department_id === null || (is_array($department_id) && count($department_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $department_id when calling getDepartmentById'
            );
        }
        if ($department_id < 1) {
            throw new \InvalidArgumentException('invalid value for "$department_id" when calling DepartmentsApi.getDepartmentById, must be bigger than or equal to 1.');
        }
        

        $resourcePath = '/api/v1/Departments/{departmentId}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($department_id !== null) {
            $resourcePath = str_replace(
                '{' . 'departmentId' . '}',
                ObjectSerializer::toPathValue($department_id),
                $resourcePath
            );
        }


        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option
     *
     * @throws \RuntimeException on file opening failure
     * @return array of http client options
     */
    protected function createHttpClientOption()
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
            }
        }

        return $options;
    }

    private function handleResponseWithDataType(
        string $dataType,
        RequestInterface $request,
        ResponseInterface $response
    ): array {
        if ($dataType === '\SplFileObject') {
            $content = $response->getBody(); //stream goes to serializer
        } else {
            $content = (string) $response->getBody();
            if ($dataType !== 'string') {
                try {
                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                } catch (\JsonException $exception) {
                    throw new ApiException(
                        sprintf(
                            'Error JSON decoding server response (%s)',
                            $request->getUri()
                        ),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                        $content
                    );
                }
            }
        }

        return [
            ObjectSerializer::deserialize($content, $dataType, []),
            $response->getStatusCode(),
            $response->getHeaders()
        ];
    }

    private function responseWithinRangeCode(
        string $rangeCode,
        int $statusCode
    ): bool {
        $left = (int) ($rangeCode[0].'00');
        $right = (int) ($rangeCode[0].'99');

        return $statusCode >= $left && $statusCode <= $right;
    }
}
