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

/**
 * API 2026-01
 *
 * Lightspeed Retail (X-Series) API.
 *
 * The version of the OpenAPI document: 2026-01
 * Contact: x-series.api@lightspeedhq.com
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.20.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 Vend202601\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 Vend202601\ApiException;
use Vend202601\Configuration;
use Vend202601\FormDataProcessor;
use Vend202601\HeaderSelector;
use Vend202601\ObjectSerializer;

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

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

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

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

    /** @var string[] $contentTypes **/
    public const contentTypes = [
        'getAuditLogEvents' => [
            'application/json',
        ],
        'getSecurityEvents' => [
            '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 getAuditLogEvents
     *
     * List audit events
     *
     * @param  string|null $page_size The size for a single page of results. By default 100 events will be returned. (optional)
     * @param  string|null $offset The number of objects to skip. (optional)
     * @param  string|null $from The lower limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $to The upper limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $order The sorting order for the results. Sorting is done by the &#x60;occurred_at&#x60; parameter. The default order is descending. (optional)
     * @param  string|null $user_id The &#x60;id&#x60; of the user to filter the events by. (optional)
     * @param  string|null $type The &#x60;type&#x60; of the events to be filtered for the response. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAuditLogEvents'] to see the possible values for this operation
     *
     * @throws \Vend202601\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return void
     */
    public function getAuditLogEvents($page_size = null, $offset = null, $from = null, $to = null, $order = null, $user_id = null, $type = null, string $contentType = self::contentTypes['getAuditLogEvents'][0])
    {
        $this->getAuditLogEventsWithHttpInfo($page_size, $offset, $from, $to, $order, $user_id, $type, $contentType);
    }

    /**
     * Operation getAuditLogEventsWithHttpInfo
     *
     * List audit events
     *
     * @param  string|null $page_size The size for a single page of results. By default 100 events will be returned. (optional)
     * @param  string|null $offset The number of objects to skip. (optional)
     * @param  string|null $from The lower limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $to The upper limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $order The sorting order for the results. Sorting is done by the &#x60;occurred_at&#x60; parameter. The default order is descending. (optional)
     * @param  string|null $user_id The &#x60;id&#x60; of the user to filter the events by. (optional)
     * @param  string|null $type The &#x60;type&#x60; of the events to be filtered for the response. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAuditLogEvents'] to see the possible values for this operation
     *
     * @throws \Vend202601\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 getAuditLogEventsWithHttpInfo($page_size = null, $offset = null, $from = null, $to = null, $order = null, $user_id = null, $type = null, string $contentType = self::contentTypes['getAuditLogEvents'][0])
    {
        $request = $this->getAuditLogEventsRequest($page_size, $offset, $from, $to, $order, $user_id, $type, $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()) {
            }
        

            throw $e;
        }
    }

    /**
     * Operation getAuditLogEventsAsync
     *
     * List audit events
     *
     * @param  string|null $page_size The size for a single page of results. By default 100 events will be returned. (optional)
     * @param  string|null $offset The number of objects to skip. (optional)
     * @param  string|null $from The lower limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $to The upper limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $order The sorting order for the results. Sorting is done by the &#x60;occurred_at&#x60; parameter. The default order is descending. (optional)
     * @param  string|null $user_id The &#x60;id&#x60; of the user to filter the events by. (optional)
     * @param  string|null $type The &#x60;type&#x60; of the events to be filtered for the response. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAuditLogEvents'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getAuditLogEventsAsync($page_size = null, $offset = null, $from = null, $to = null, $order = null, $user_id = null, $type = null, string $contentType = self::contentTypes['getAuditLogEvents'][0])
    {
        return $this->getAuditLogEventsAsyncWithHttpInfo($page_size, $offset, $from, $to, $order, $user_id, $type, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getAuditLogEventsAsyncWithHttpInfo
     *
     * List audit events
     *
     * @param  string|null $page_size The size for a single page of results. By default 100 events will be returned. (optional)
     * @param  string|null $offset The number of objects to skip. (optional)
     * @param  string|null $from The lower limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $to The upper limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $order The sorting order for the results. Sorting is done by the &#x60;occurred_at&#x60; parameter. The default order is descending. (optional)
     * @param  string|null $user_id The &#x60;id&#x60; of the user to filter the events by. (optional)
     * @param  string|null $type The &#x60;type&#x60; of the events to be filtered for the response. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAuditLogEvents'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getAuditLogEventsAsyncWithHttpInfo($page_size = null, $offset = null, $from = null, $to = null, $order = null, $user_id = null, $type = null, string $contentType = self::contentTypes['getAuditLogEvents'][0])
    {
        $returnType = '';
        $request = $this->getAuditLogEventsRequest($page_size, $offset, $from, $to, $order, $user_id, $type, $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 'getAuditLogEvents'
     *
     * @param  string|null $page_size The size for a single page of results. By default 100 events will be returned. (optional)
     * @param  string|null $offset The number of objects to skip. (optional)
     * @param  string|null $from The lower limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $to The upper limit for the &#x60;occurred_at&#x60; attribute. to be included in the response. The date and time from needs to be in isoformat. (optional)
     * @param  string|null $order The sorting order for the results. Sorting is done by the &#x60;occurred_at&#x60; parameter. The default order is descending. (optional)
     * @param  string|null $user_id The &#x60;id&#x60; of the user to filter the events by. (optional)
     * @param  string|null $type The &#x60;type&#x60; of the events to be filtered for the response. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAuditLogEvents'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getAuditLogEventsRequest($page_size = null, $offset = null, $from = null, $to = null, $order = null, $user_id = null, $type = null, string $contentType = self::contentTypes['getAuditLogEvents'][0])
    {

        if ($page_size !== null && strlen($page_size) > 100) {
            throw new \InvalidArgumentException('invalid length for "$page_size" when calling AuditApi.getAuditLogEvents, must be smaller than or equal to 100.');
        }
        
        if ($offset !== null && strlen($offset) > 0) {
            throw new \InvalidArgumentException('invalid length for "$offset" when calling AuditApi.getAuditLogEvents, must be smaller than or equal to 0.');
        }
        






        $resourcePath = '/auditlog_events';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page_size,
            'page_size', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $offset,
            'offset', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $from,
            'from', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $to,
            'to', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $order,
            'order', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $user_id,
            'user_id', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $type,
            'type', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);




        $headers = $this->headerSelector->selectHeaders(
            ['Insert of product example', '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 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 getSecurityEvents
     *
     * List security events for current user
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getSecurityEvents'] to see the possible values for this operation
     *
     * @throws \Vend202601\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return void
     */
    public function getSecurityEvents(string $contentType = self::contentTypes['getSecurityEvents'][0])
    {
        $this->getSecurityEventsWithHttpInfo($contentType);
    }

    /**
     * Operation getSecurityEventsWithHttpInfo
     *
     * List security events for current user
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getSecurityEvents'] to see the possible values for this operation
     *
     * @throws \Vend202601\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 getSecurityEventsWithHttpInfo(string $contentType = self::contentTypes['getSecurityEvents'][0])
    {
        $request = $this->getSecurityEventsRequest($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()) {
            }
        

            throw $e;
        }
    }

    /**
     * Operation getSecurityEventsAsync
     *
     * List security events for current user
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getSecurityEvents'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSecurityEventsAsync(string $contentType = self::contentTypes['getSecurityEvents'][0])
    {
        return $this->getSecurityEventsAsyncWithHttpInfo($contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getSecurityEventsAsyncWithHttpInfo
     *
     * List security events for current user
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getSecurityEvents'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSecurityEventsAsyncWithHttpInfo(string $contentType = self::contentTypes['getSecurityEvents'][0])
    {
        $returnType = '';
        $request = $this->getSecurityEventsRequest($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 'getSecurityEvents'
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getSecurityEvents'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getSecurityEventsRequest(string $contentType = self::contentTypes['getSecurityEvents'][0])
    {


        $resourcePath = '/security_events';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['Security signin example', '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 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());
            }
        }

        if ($this->config->getCertFile()) {
            $options[RequestOptions::CERT] = $this->config->getCertFile();
        }

        if ($this->config->getKeyFile()) {
            $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile();
        }

        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;
    }
}
