<?php

// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.

namespace Algolia\AlgoliaSearch\Api;

use Algolia\AlgoliaSearch\Algolia;
use Algolia\AlgoliaSearch\Configuration\PersonalizationConfig;
use Algolia\AlgoliaSearch\Model\Personalization\DeleteUserProfileResponse;
use Algolia\AlgoliaSearch\Model\Personalization\GetUserTokenResponse;
use Algolia\AlgoliaSearch\Model\Personalization\PersonalizationStrategyParams;
use Algolia\AlgoliaSearch\Model\Personalization\SetPersonalizationStrategyResponse;
use Algolia\AlgoliaSearch\ObjectSerializer;
use Algolia\AlgoliaSearch\RetryStrategy\AlgoliaResponse;
use Algolia\AlgoliaSearch\RetryStrategy\ApiWrapper;
use Algolia\AlgoliaSearch\RetryStrategy\ApiWrapperInterface;
use Algolia\AlgoliaSearch\RetryStrategy\ClusterHosts;
use GuzzleHttp\Psr7\Query;

/**
 * PersonalizationClient Class Doc Comment.
 *
 * @category Class
 */
class PersonalizationClient
{
    public const VERSION = '4.46.2';

    /**
     * @var ApiWrapperInterface
     */
    protected $api;

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

    public function __construct(ApiWrapperInterface $apiWrapper, PersonalizationConfig $config)
    {
        $this->config = $config;
        $this->api = $apiWrapper;
    }

    /**
     * Instantiate the client with basic credentials and region.
     *
     * @param string $appId  Application ID
     * @param string $apiKey Algolia API Key
     * @param string $region Region
     */
    public static function create($appId = null, $apiKey = null, $region = null)
    {
        $config = PersonalizationConfig::create($appId, $apiKey, $region);

        return static::createWithConfig($config);
    }

    /**
     * Instantiate the client with configuration.
     *
     * @param PersonalizationConfig $config Configuration
     */
    public static function createWithConfig(PersonalizationConfig $config)
    {
        $config = clone $config;

        $apiWrapper = new ApiWrapper(
            Algolia::getHttpClient(),
            $config,
            self::getClusterHosts($config)
        );

        $client = new static($apiWrapper, $config);

        $logger = Algolia::getLogger();
        $logger->info('Algolia API client: Algolia PersonalizationClient initialized (appId: '.$config->getAppId().')');
        Algolia::logDebugWarningOnce();

        return $client;
    }

    /**
     * Gets the cluster hosts depending on the config.
     *
     * @return ClusterHosts
     */
    public static function getClusterHosts(PersonalizationConfig $config)
    {
        if ($hosts = $config->getHosts()) {
            // If a list of hosts was passed, we ignore the cache
            $clusterHosts = ClusterHosts::create($hosts);
        } else {
            $url = null !== $config->getRegion() && '' !== $config->getRegion()
                ? str_replace('{region}', $config->getRegion(), 'personalization.{region}.algolia.com')
                : '';
            $clusterHosts = ClusterHosts::create($url);
        }

        return $clusterHosts;
    }

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

    /**
     * Stub method setting a new API key to authenticate requests.
     *
     * @param string $apiKey
     */
    public function setClientApiKey($apiKey)
    {
        $this->config->setClientApiKey($apiKey);
    }

    /**
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|object
     */
    public function customDelete($path, $parameters = null, $requestOptions = [])
    {
        $response = $this->customDeleteWithHttpInfo($path, $parameters, $requestOptions);

        return $response->getData();
    }

    /**
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|object
     */
    public function customGet($path, $parameters = null, $requestOptions = [])
    {
        $response = $this->customGetWithHttpInfo($path, $parameters, $requestOptions);

        return $response->getData();
    }

    /**
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $body           Parameters to send with the custom request. (optional)
     * @param array  $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|object
     */
    public function customPost($path, $parameters = null, $body = null, $requestOptions = [])
    {
        $response = $this->customPostWithHttpInfo($path, $parameters, $body, $requestOptions);

        return $response->getData();
    }

    /**
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $body           Parameters to send with the custom request. (optional)
     * @param array  $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|object
     */
    public function customPut($path, $parameters = null, $body = null, $requestOptions = [])
    {
        $response = $this->customPutWithHttpInfo($path, $parameters, $body, $requestOptions);

        return $response->getData();
    }

    /**
     * Deletes a user profile.  The response includes a date and time when the user profile can safely be considered deleted.
     *
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param string $userToken      Unique identifier representing a user for which to fetch the personalization profile. (required)
     * @param array  $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|DeleteUserProfileResponse
     */
    public function deleteUserProfile($userToken, $requestOptions = [])
    {
        $response = $this->deleteUserProfileWithHttpInfo($userToken, $requestOptions);

        return $response->getData();
    }

    /**
     * Retrieves the current personalization strategy.
     *
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param array $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|PersonalizationStrategyParams
     */
    public function getPersonalizationStrategy($requestOptions = [])
    {
        $response = $this->getPersonalizationStrategyWithHttpInfo($requestOptions);

        return $response->getData();
    }

    /**
     * Retrieves a user profile and their affinities for different facets.
     *
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param string $userToken      Unique identifier representing a user for which to fetch the personalization profile. (required)
     * @param array  $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|GetUserTokenResponse
     */
    public function getUserTokenProfile($userToken, $requestOptions = [])
    {
        $response = $this->getUserTokenProfileWithHttpInfo($userToken, $requestOptions);

        return $response->getData();
    }

    /**
     * Creates a new personalization strategy.
     *
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param array|PersonalizationStrategyParams $personalizationStrategyParams personalizationStrategyParams (required)
     *                                                                           - $personalizationStrategyParams['eventsScoring'] => (array) Scores associated with each event.  The higher the scores, the higher the impact of those events on the personalization of search results. (required)
     *                                                                           - $personalizationStrategyParams['facetsScoring'] => (array) Scores associated with each facet.  The higher the scores, the higher the impact of those events on the personalization of search results. (required)
     *                                                                           - $personalizationStrategyParams['personalizationImpact'] => (int) Impact of personalization on the search results.  If set to 0, personalization has no impact on the search results. (required)
     *
     * @see PersonalizationStrategyParams
     *
     * @param array $requestOptions the requestOptions to send along with the query, they will be merged with the transporter requestOptions
     *
     * @return array<string, mixed>|SetPersonalizationStrategyResponse
     */
    public function setPersonalizationStrategy($personalizationStrategyParams, $requestOptions = [])
    {
        $response = $this->setPersonalizationStrategyWithHttpInfo($personalizationStrategyParams, $requestOptions);

        return $response->getData();
    }

    /**
     * Send requests to the Algolia REST API (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function customDeleteWithHttpInfo($path, $parameters = null, $requestOptions = [])
    {
        // verify the required parameter 'path' is set
        if (!isset($path)) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customDelete`.'
            );
        }
        // verify the required parameter 'path' is not empty
        if (isset($path) && '' === $path) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customDelete`.'
            );
        }

        $resourcePath = '/{path}';
        $queryParameters = [];
        $headers = [];
        $httpBody = null;

        if (null !== $parameters) {
            $queryParameters = $parameters;
        }

        // path params
        if (null !== $path) {
            $resourcePath = str_replace(
                '{path}',
                $path,
                $resourcePath
            );
        }

        return $this->sendRequestWithHttpInfo('DELETE', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Send requests to the Algolia REST API (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function customGetWithHttpInfo($path, $parameters = null, $requestOptions = [])
    {
        // verify the required parameter 'path' is set
        if (!isset($path)) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customGet`.'
            );
        }
        // verify the required parameter 'path' is not empty
        if (isset($path) && '' === $path) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customGet`.'
            );
        }

        $resourcePath = '/{path}';
        $queryParameters = [];
        $headers = [];
        $httpBody = null;

        if (null !== $parameters) {
            $queryParameters = $parameters;
        }

        // path params
        if (null !== $path) {
            $resourcePath = str_replace(
                '{path}',
                $path,
                $resourcePath
            );
        }

        return $this->sendRequestWithHttpInfo('GET', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Send requests to the Algolia REST API (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $body           Parameters to send with the custom request. (optional)
     * @param array  $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function customPostWithHttpInfo($path, $parameters = null, $body = null, $requestOptions = [])
    {
        // verify the required parameter 'path' is set
        if (!isset($path)) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customPost`.'
            );
        }
        // verify the required parameter 'path' is not empty
        if (isset($path) && '' === $path) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customPost`.'
            );
        }

        $resourcePath = '/{path}';
        $queryParameters = [];
        $headers = [];
        $httpBody = isset($body) ? $body : [];

        if (null !== $parameters) {
            $queryParameters = $parameters;
        }

        // path params
        if (null !== $path) {
            $resourcePath = str_replace(
                '{path}',
                $path,
                $resourcePath
            );
        }

        return $this->sendRequestWithHttpInfo('POST', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Send requests to the Algolia REST API (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * This method lets you send requests to the Algolia REST API.
     *
     * @param string $path           Path of the endpoint, for example `1/newFeature`. (required)
     * @param array  $parameters     Query parameters to apply to the current query. (optional)
     * @param array  $body           Parameters to send with the custom request. (optional)
     * @param array  $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function customPutWithHttpInfo($path, $parameters = null, $body = null, $requestOptions = [])
    {
        // verify the required parameter 'path' is set
        if (!isset($path)) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customPut`.'
            );
        }
        // verify the required parameter 'path' is not empty
        if (isset($path) && '' === $path) {
            throw new \InvalidArgumentException(
                'Parameter `path` is required when calling `customPut`.'
            );
        }

        $resourcePath = '/{path}';
        $queryParameters = [];
        $headers = [];
        $httpBody = isset($body) ? $body : [];

        if (null !== $parameters) {
            $queryParameters = $parameters;
        }

        // path params
        if (null !== $path) {
            $resourcePath = str_replace(
                '{path}',
                $path,
                $resourcePath
            );
        }

        return $this->sendRequestWithHttpInfo('PUT', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Delete a user profile (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * Deletes a user profile.  The response includes a date and time when the user profile can safely be considered deleted.
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param string $userToken      Unique identifier representing a user for which to fetch the personalization profile. (required)
     * @param array  $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function deleteUserProfileWithHttpInfo($userToken, $requestOptions = [])
    {
        // verify the required parameter 'userToken' is set
        if (!isset($userToken)) {
            throw new \InvalidArgumentException(
                'Parameter `userToken` is required when calling `deleteUserProfile`.'
            );
        }
        // verify the required parameter 'userToken' is not empty
        if (isset($userToken) && '' === $userToken) {
            throw new \InvalidArgumentException(
                'Parameter `userToken` is required when calling `deleteUserProfile`.'
            );
        }

        $resourcePath = '/1/profiles/{userToken}';
        $queryParameters = [];
        $headers = [];
        $httpBody = null;

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

        return $this->sendRequestWithHttpInfo('DELETE', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Retrieve the personalization strategy (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * Retrieves the current personalization strategy.
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param array $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function getPersonalizationStrategyWithHttpInfo($requestOptions = [])
    {
        $resourcePath = '/1/strategies/personalization';
        $queryParameters = [];
        $headers = [];
        $httpBody = null;

        return $this->sendRequestWithHttpInfo('GET', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Retrieve a user profile (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * Retrieves a user profile and their affinities for different facets.
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param string $userToken      Unique identifier representing a user for which to fetch the personalization profile. (required)
     * @param array  $requestOptions Request options
     *
     * @return AlgoliaResponse
     */
    public function getUserTokenProfileWithHttpInfo($userToken, $requestOptions = [])
    {
        // verify the required parameter 'userToken' is set
        if (!isset($userToken)) {
            throw new \InvalidArgumentException(
                'Parameter `userToken` is required when calling `getUserTokenProfile`.'
            );
        }
        // verify the required parameter 'userToken' is not empty
        if (isset($userToken) && '' === $userToken) {
            throw new \InvalidArgumentException(
                'Parameter `userToken` is required when calling `getUserTokenProfile`.'
            );
        }

        $resourcePath = '/1/profiles/personalization/{userToken}';
        $queryParameters = [];
        $headers = [];
        $httpBody = null;

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

        return $this->sendRequestWithHttpInfo('GET', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    /**
     * Define the personalization strategy (with HTTP info).
     *
     * Returns the response with HTTP metadata (status code, headers, body)
     * Creates a new personalization strategy.
     * Required API Key ACLs:
     *  - recommendation
     *
     * @param array|PersonalizationStrategyParams $personalizationStrategyParams (required)
     * @param array                               $requestOptions                Request options
     *
     * @return AlgoliaResponse
     */
    public function setPersonalizationStrategyWithHttpInfo($personalizationStrategyParams, $requestOptions = [])
    {
        // verify the required parameter 'personalizationStrategyParams' is set
        if (!isset($personalizationStrategyParams)) {
            throw new \InvalidArgumentException(
                'Parameter `personalizationStrategyParams` is required when calling `setPersonalizationStrategy`.'
            );
        }

        $resourcePath = '/1/strategies/personalization';
        $queryParameters = [];
        $headers = [];
        $httpBody = $personalizationStrategyParams;

        return $this->sendRequestWithHttpInfo('POST', $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions);
    }

    private function sendRequestWithHttpInfo($method, $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions, $useReadTransporter = false)
    {
        if (!isset($requestOptions['headers'])) {
            $requestOptions['headers'] = [];
        }
        if (!isset($requestOptions['queryParameters'])) {
            $requestOptions['queryParameters'] = [];
        }

        $requestOptions['headers'] = array_merge($headers, $requestOptions['headers']);
        $requestOptions['queryParameters'] = array_merge($queryParameters, $requestOptions['queryParameters']);
        $query = Query::build($requestOptions['queryParameters']);

        return $this->api->sendRequest(
            $method,
            $resourcePath.($query ? "?{$query}" : ''),
            $httpBody,
            $requestOptions,
            $useReadTransporter,
            true
        );
    }
}
