<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Model\Api;

use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use WriteTextAI\WriteTextAI\Model\Api\CurlBuilder;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\KeywordIdeaFiltersManager;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use WriteTextAI\WriteTextAI\Model\Config\Source\TriggerActions;
use WriteTextAI\WriteTextAI\Model\Config\Source\AutomaticTextOptimization;

/**
 * @api
 */
class Keywords
{
    /**
     * @var RemoteAddress
     */
    protected $remoteAddress;

    /**
     * @var CurlBuilder
     */
    protected $curlBuilder;

    /**
     * @var StoreHelper
     */
    protected $storeHelper;

    /**
     * @var Data
     */
    protected $helper;

    /**
     * @var KeywordIdeaFiltersManager
     */
    protected $keywordIdeaFiltersManager;

    /**
     * @var string
     */
    protected $ipAddress = '';

    /**
     * Constructor
     *
     * @param RemoteAddress $remoteAddress
     * @param CurlBuilder $curlBuilder
     * @param StoreHelper $storeHelper
     * @param Data $helper
     * @param KeywordIdeaFiltersManager $keywordIdeaFiltersManager
     */
    public function __construct(
        RemoteAddress $remoteAddress,
        CurlBuilder $curlBuilder,
        StoreHelper $storeHelper,
        Data $helper,
        KeywordIdeaFiltersManager $keywordIdeaFiltersManager
    ) {
        $this->remoteAddress = $remoteAddress;
        $this->curlBuilder = $curlBuilder;
        $this->storeHelper = $storeHelper;
        $this->helper = $helper;
        $this->keywordIdeaFiltersManager = $keywordIdeaFiltersManager;
    }
    
    /**
     * Get keyword state
     *
     * @param string $storeId
     * @param array $states
     * @param string $token
     * @param string $type
     *
     * @return array
     */
    public function getKeywordState(
        $storeId,
        $states,
        $token = null,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);

            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "languageCode" => $storeLanguage,
                "states" => $states,
                "continuationToken" => $token
            ];

            $response = $this->curlBuilder->getApiResponse('text/Keywords/Optimization/Pipelines/KeywordState', $body);
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }

        return $response;
    }
    
    /**
     * Get keywords optimization
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $type
     *
     * @return array
     */
    public function getOptimization(
        $storeId,
        $recordId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponse('text/Keywords/Optimization', $body);
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }
    
    /**
     * Get keywords optimization list
     *
     * @param string $storeId
     * @param array $status
     * @param string $token
     * @param string $type
     * @param array $ids
     *
     * @return array
     */
    public function getOptimizationList(
        $storeId,
        $status = [],
        $token = null,
        $type = 'Product',
        $ids = []
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => (string) $storeId,
                "type" => $type,
                "languageCode" => $storeLanguage,
                "status" => !empty($status) ? $status : null,
                "continuationToken" => $token
            ];

            if (!empty($ids)) {
                $body['RecordIds'] = $ids;
                $body['PageSize'] = count($ids);
            }

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/List',
                json_encode($body),
                'post'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Update keywords optimization image
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $imageId
     * @param string $type
     *
     * @return array
     */
    public function updateOptimizationImage(
        $storeId,
        $recordId,
        $imageId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "imageId" => $imageId
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization',
                json_encode($body),
                'post'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Update keywords optimization
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $url
     * @param string $name
     * @param array $intent
     * @param array $seedKeywords
     * @param string $type
     * @param array $products
     * @param string $imageId
     *
     * @return array
     */
    public function updateOptimization(
        $storeId,
        $recordId,
        $url,
        $name,
        $intent,
        $seedKeywords = [],
        $type = 'Product',
        $products = [],
        $imageId = null
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $ipAddress = $this->getIpAddress();

            $clusterCount = $this->helper->getKeywordOptimizationSettings('cluster_based_pipelines_count');
            if ($type === 'Category') {
                $clusterCount = $this->helper->getKeywordOptimizationSettings('cluster_based_pipelines_count_category');
            }
            
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "ipAddress" => $ipAddress,
                "url" => $this->helper->getKoStaticUrl() ? $this->helper->getKoStaticUrl() : $url,
                "name" => $name,
                "intents" => $intent,
                "countryCode" => $this->keywordIdeaFiltersManager->getCountryCode($storeId),
                "development" => filter_var($this->helper->getKoDev(), FILTER_VALIDATE_BOOLEAN),
                "clusters" => $clusterCount
            ];
            
            if ($this->helper->getForceQueueSeconds()) {
                $body['developmentQueueWaitTimeInSeconds'] = $this->helper->getForceQueueSeconds();
            }
            if ($type === 'Category') {
                $body['products'] = $products;
            }
            $triggerSettings = $this->prepareDefaultTriggerSettingsParameters($type);
            if (!empty($triggerSettings)) {
                $body['triggers'] = $triggerSettings;
            }

            /**
             * if (!empty($seedKeywords)) {
             *  $body['seedKeywords'] = $seedKeywords;
             * }
             */
            if ($imageId) {
                $body['imageId'] = $imageId;
            }
        
            if (filter_var($this->helper->getKoDev(), FILTER_VALIDATE_BOOLEAN)) {
                $body["developmentSettings"] = [
                    "waitTimePerStep" => 1000,
                    "maxSteps" => 9,
                    "failAfterFirstStep" => filter_var($this->helper->getForceFailed(), FILTER_VALIDATE_BOOLEAN)
                ];
            }
            
            $response = $this->curlBuilder->getApiResponseCustom(
                'text/Keywords/Optimization',
                json_encode($body),
                'put'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Delete keywords optimization
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $type
     *
     * @return array
     */
    public function deleteOptimization(
        $storeId,
        $recordId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponseCustom('text/Keywords/Optimization', $body, 'delete');
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Save manual keywords
     *
     * @param string $storeId
     * @param string $recordId
     * @param array $keywords
     * @param string $type
     *
     * @return array
     */
    public function saveManualKeywords(
        $storeId,
        $recordId,
        $keywords = [],
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "manualKeywords" => $keywords
            ];

            $response = $this->curlBuilder->getApiResponse('text/Keywords', json_encode($body), 'post');
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Get IP address
     *
     * @return string
     */
    public function getIpAddress()
    {
        if ($this->ipAddress === '') {
            $this->ipAddress = $this->remoteAddress->getRemoteAddress();
        }

        return $this->ipAddress;
    }

    /**
     * Create pipeline
     *
     * @param string $storeId
     * @param string $recordId
     * @param array $keywords
     * @param string $type
     *
     * @return array
     */
    public function createPipeline(
        $storeId,
        $recordId,
        $keywords,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "keywords" => $keywords
            ];
            /** Send all default triggers as per API requirements */
            $defaultTriggerSettings = $this->prepareDefaultTriggerSettingsParameters($type);
            $body['triggers'] = $defaultTriggerSettings;

            $response = $this->curlBuilder->getApiResponseCustom(
                'text/Keywords/Optimization/Pipelines',
                json_encode($body),
                'put'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Update pipeline
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $pipelineId
     * @param array $keywords
     * @param array $triggers
     * @param string $type
     *
     * @return array
     */
    public function updatePipeline(
        $storeId,
        $recordId,
        $pipelineId,
        $keywords,
        $triggers,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $defaultTriggerSettings = $this->prepareDefaultTriggerSettingsParameters($type);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "keywords" => $keywords
            ];
            foreach ($keywords as $difficulty => $keyword) {
                if ($difficulty === 'High') {
                    continue;
                }
                $body['triggers'][$difficulty] = $triggers[$difficulty] ?? $defaultTriggerSettings[$difficulty] ?? [];
            }

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Pipelines/'.$pipelineId,
                json_encode($body),
                'post'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Delete pipeline
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $pipelineId
     * @param string $type
     *
     * @return array
     */
    public function deletePipeline(
        $storeId,
        $recordId,
        $pipelineId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponseCustom(
                'text/Keywords/Optimization/Pipelines/'.$pipelineId,
                $body,
                'delete'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Add keyword to pool
     *
     * @param string $storeId
     * @param string $recordId
     * @param array $keyword
     * @param string $type
     *
     * @return array
     */
    public function addKeywordsToPool(
        $storeId,
        $recordId,
        $keyword,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "keyword" => $keyword
            ];

            $response = $this->curlBuilder->getApiResponseCustom(
                'text/Keywords/Optimization/Keywords',
                json_encode($body),
                'put'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Restore pipeline
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $type
     *
     * @return array
     */
    public function restorePipeline(
        $storeId,
        $recordId,
        $type = 'Product'
    ) {
        try {
            $triggerSettings = $this->prepareDefaultTriggerSettingsParameters($type);
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "triggers" => $triggerSettings
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Pipelines/Restore',
                json_encode($body),
                'post'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * GET snapshot
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $snapshotId
     * @param string $type
     *
     * @return array
     */
    public function getSnapshot(
        $storeId,
        $recordId,
        $snapshotId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Snapshots/'.$snapshotId,
                $body
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Create snapshot
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $type
     *
     * @return array
     */
    public function createSnapshot(
        $storeId,
        $recordId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponseCustom(
                'text/Keywords/Optimization/Snapshots',
                json_encode($body),
                'put'
            );

            $snapshotId = $response['snapshot']['id'] ?? '';
            if ($snapshotId) {
                $response = $this->getSnapshot($storeId, $recordId, $snapshotId, $type);
                return $response;
            }
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Lock pipeline
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $pipelineId
     * @param string $type
     *
     * @return array
     */
    public function lockPipeline(
        $storeId,
        $recordId,
        $pipelineId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Pipelines/'.$pipelineId.'/Lock',
                json_encode($body),
                'post'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Unlock pipeline
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $pipelineId
     * @param string $type
     *
     * @return array
     */
    public function unlockPipeline(
        $storeId,
        $recordId,
        $pipelineId,
        $type = 'Product'
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Pipelines/'.$pipelineId.'/Unlock',
                json_encode($body),
                'post'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Get the default trigger settings
     *
     * @param string $entityType
     * @param array $difficulties
     *
     * @return array
     */
    public function prepareDefaultTriggerSettingsParameters(
        $entityType = 'Product',
        $difficulties = []
    ) {
        try {
            $defaultSettings = [];

            $triggerSettings = $this->helper->getKeywordOptimizationSettings();

            $defaultSettings = $this->processTriggerSettingsData($entityType, $triggerSettings, $difficulties);
        } catch (\Exception $e) {
            $defaultSettings = [];
        }

        return $defaultSettings;
    }

    /**
     * Prepare custom trigger settings parameters
     *
     * @param string $entityType
     * @param array $triggerSettings
     *
     * @return array
     */
    public function prepareCustomTriggerSettingsParameters(
        $entityType,
        $triggerSettings
    ) {
        try {
            $defaultSettings = $this->processTriggerSettingsData($entityType, $triggerSettings);
        } catch (\Exception $e) {
            $defaultSettings = [];
        }

        return $defaultSettings;
    }

    /**
     * Build trigger settings
     *
     * @param string $entityType
     * @param array $triggerSettings
     * @param array $difficulties
     *
     * @return array
     */
    public function processTriggerSettingsData(
        $entityType,
        $triggerSettings,
        $difficulties = []
    ) {
            
        $selectedTextTypes = [];
        if ($entityType == 'Product') {
            $fieldsMapping = [
                'page_title' => Fields::PAGE_TITLE,
                'page_description' => Fields::PAGE_DESCRIPTION,
                'product_description' => Fields::PRODUCT_DESCRIPTION,
                'short_product_description' => Fields::EXCERPT,
                'open_graph' => Fields::OPEN_GRAPH
            ];
            $selectedTextTypes = isset($triggerSettings['products'])
                ? explode(',', $triggerSettings['products']) : [];
        } else {
            $fieldsMapping = Fields::CATEGORY_MAPPING;
            $selectedTextTypes = isset($triggerSettings['categories'])
                ? explode(',', $triggerSettings['categories']) : [];
        }

        $difficultyEquivalents = [
            'low' => 'Low',
            'low_mid' => 'LowMid',
            'mid' => 'Mid',
            'mid_high' => 'MidHigh'
        ];
        if (empty($difficulties)) {
            $difficulties = array_keys($difficultyEquivalents);
        }
        
        $configTextTypes = $triggerSettings['text_types'] ?? [];
        foreach ($difficulties as $difficulty) {
            $difficulitySetting = $difficultyEquivalents[$difficulty];
            if (isset($triggerSettings['pipeline_keyword'][$difficulty])) {
                switch ($triggerSettings['pipeline_keyword'][$difficulty]['trigger_action']) {
                    case TriggerActions::WHEN_PAGE_IS_RANKING:
                        $defaultSettings[$difficulitySetting]['option'] = 'WhenRanking';
                        $defaultSettings[$difficulitySetting]['value'] =
                            $triggerSettings['pipeline_keyword'][$difficulty]['trigger_action_n_position'];
                        break;
                    case TriggerActions::AFTER_N_DAYS:
                        $defaultSettings[$difficulitySetting]['option'] = 'AfterSetDays';
                        $defaultSettings[$difficulitySetting]['value'] =
                            $triggerSettings['pipeline_keyword'][$difficulty]['trigger_action_n_days'];
                        break;
                    case TriggerActions::NONE:
                        $defaultSettings[$difficulitySetting]['option'] = 'None';
                        break;
                }
            }

            switch ($triggerSettings['automatic_text_optimization']) {
                case AutomaticTextOptimization::AUTO_REWRITE_AND_QUEUE:
                    $defaultSettings[$difficulitySetting]['action'] = 'AutomaticRewrite';
                    break;
                case AutomaticTextOptimization::FLAG:
                    $defaultSettings[$difficulitySetting]['action'] = 'FlagForRewrite';
                    break;
                case AutomaticTextOptimization::AUTO_REWRITE_AND_TRANSFER:
                    $defaultSettings[$difficulitySetting]['action'] = 'FullAutomation';
                    break;
            }
            
            if (!empty($selectedTextTypes)) {
                foreach ($selectedTextTypes as $textType) {
                    $defaultSettings[$difficulitySetting]['textTypes'][] = $fieldsMapping[$textType] ?? $textType;
                }
            }
        }

        return $defaultSettings;
    }

    /**
     * Update pipeline trigger settings
     *
     * @param string $storeId
     * @param string $recordId
     * @param mixed $pipelineId
     * @param array $difficulties
     * @param string $option
     * @param string $value
     * @param string $action
     * @param array $textTypes
     * @param string $type
     *
     * @return array
     */
    public function updatePipelineTriggerSettings(
        $storeId,
        $recordId,
        $pipelineId,
        $difficulties,
        $option,
        $value,
        $action,
        $textTypes,
        $type = 'Product'
    ) {
        try {
            $triggerSettings = $this->prepareTriggerSettingsParameter(
                $difficulties,
                $option,
                $value,
                $action,
                $textTypes
            );
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "triggers" => $triggerSettings
            ];
            if (is_array($pipelineId)) {
                foreach ($pipelineId as $id) {
                    $response = $this->curlBuilder->getApiResponse(
                        'text/Keywords/Optimization/Pipelines/'.$id.'/Triggers',
                        json_encode($body),
                        'post'
                    );
                }
            } else {
                $response = $this->curlBuilder->getApiResponse(
                    'text/Keywords/Optimization/Pipelines/'.$pipelineId.'/Triggers',
                    json_encode($body),
                    'post'
                );
            }
            $response = $triggerSettings;
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Update pipeline trigger settings
     *
     * @param string $storeId
     * @param string $recordId
     * @param mixed $pipelines
     * @param array $difficulties
     * @param string $option
     * @param string $value
     * @param string $action
     * @param array $textTypes
     * @param string $type
     *
     * @return array
     */
    public function updateMultiplePipelineTriggerSettingsViaPipelines(
        $storeId,
        $recordId,
        $pipelines,
        $difficulties,
        $option,
        $value,
        $action,
        $textTypes,
        $type = 'Product'
    ) {
        try {
            $triggerSettings = [];
            $responseValue = [];
            $pipelineIdsUpdated = [];

            foreach ($pipelines as $pipeline) {
                $triggerSettings = $this->prepareTriggerSettingsParameterPerPipeline(
                    $pipeline,
                    $difficulties,
                    $option,
                    $value,
                    $action,
                    $textTypes
                );

                if (empty($triggerSettings)) {
                    continue;
                }
                
                $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);

                $body = [
                    "storeId" => $storeId,
                    "type" => $type,
                    "recordId" => $recordId,
                    "languageCode" => $storeLanguage,
                    "triggers" => $triggerSettings
                ];

                $response = $this->curlBuilder->getApiResponse(
                    'text/Keywords/Optimization/Pipelines/'.$pipeline['id'].'/Triggers',
                    json_encode($body),
                    'post'
                );
                $responseValue[] = [
                    'id' => $pipeline['id'],
                    'triggers' => $triggerSettings
                ];
            }

            $response = $responseValue;
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Update multiple pipeline trigger settings
     *
     * @param string $storeId
     * @param string $recordId
     * @param array $difficulties
     * @param string $option
     * @param string $value
     * @param string $action
     * @param array $textTypes
     * @param string $type
     *
     * @return array
     */
    public function updateMultiplePipelineTriggerSettings(
        $storeId,
        $recordId,
        $difficulties,
        $option,
        $value,
        $action,
        $textTypes,
        $type = 'Product'
    ) {
        try {
            $triggerSettings = $this->prepareTriggerSettingsParameter(
                $difficulties,
                $option,
                $value,
                $action,
                $textTypes
            );
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "triggers" => $triggerSettings
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Pipelines/Triggers',
                json_encode($body),
                'post'
            );
            $response = $triggerSettings;
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Update global trigger settings
     *
     * @param array $triggerSettings
     * @param string $type
     *
     * @return array
     */
    public function updateGlobalTriggerSettings(
        $triggerSettings,
        $type = 'Product'
    ) {
        try {
            $body = [
                "type" => $type,
                "triggers" => $triggerSettings
            ];

            $response = $this->curlBuilder->getApiResponse(
                'text/Keywords/Optimization/Pipelines/Triggers',
                json_encode($body),
                'post'
            );
            $response = $triggerSettings;
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }

    /**
     * Prepare trigger settings parameter
     *
     * @param array $difficulties
     * @param string $option
     * @param string $value
     * @param string $action
     * @param array $textTypes
     *
     * @return array
     */
    public function prepareTriggerSettingsParameter(
        $difficulties,
        $option,
        $value,
        $action,
        $textTypes
    ) {
        $triggerSettings = [];
        $optionEquivalent = '';
        $actionEquivalent = '';

        switch ($option) {
            case TriggerActions::WHEN_PAGE_IS_RANKING:
                $optionEquivalent = 'WhenRanking';
                break;
            case TriggerActions::AFTER_N_DAYS:
                $optionEquivalent = 'AfterSetDays';
                break;
            case TriggerActions::NONE:
                $optionEquivalent = 'None';
                break;
            default:
                $optionEquivalent = $option;
                break;
        }

        switch ($action) {
            case AutomaticTextOptimization::AUTO_REWRITE_AND_QUEUE:
                $actionEquivalent = 'AutomaticRewrite';
                break;
            case AutomaticTextOptimization::FLAG:
                $actionEquivalent = 'FlagForRewrite';
                break;
            case AutomaticTextOptimization::AUTO_REWRITE_AND_TRANSFER:
                $actionEquivalent = 'FullAutomation';
                break;
            default:
                $actionEquivalent = $action;
                break;
        }

        foreach ($difficulties as $difficulty) {
            $triggerSettings[$difficulty] = [
                'option' => $optionEquivalent,
                'value' => $value,
                'action' => $actionEquivalent,
                'textTypes' => $textTypes ?? []
            ];
        }
        return $triggerSettings;
    }

    /**
     * Prepare trigger settings parameter
     *
     * @param array $pipeline
     * @param array $difficulties
     * @param string $option
     * @param string $value
     * @param string $action
     * @param array $textTypes
     *
     * @return array
     */
    public function prepareTriggerSettingsParameterPerPipeline(
        $pipeline,
        $difficulties,
        $option,
        $value,
        $action,
        $textTypes
    ) {
        $triggerSettings = [];
        $optionEquivalent = '';
        $actionEquivalent = '';

        switch ($option) {
            case TriggerActions::WHEN_PAGE_IS_RANKING:
                $optionEquivalent = 'WhenRanking';
                break;
            case TriggerActions::AFTER_N_DAYS:
                $optionEquivalent = 'AfterSetDays';
                break;
            case TriggerActions::NONE:
                $optionEquivalent = 'None';
                break;
            default:
                $optionEquivalent = $option;
                break;
        }

        switch ($action) {
            case AutomaticTextOptimization::AUTO_REWRITE_AND_QUEUE:
                $actionEquivalent = 'AutomaticRewrite';
                break;
            case AutomaticTextOptimization::FLAG:
                $actionEquivalent = 'FlagForRewrite';
                break;
            case AutomaticTextOptimization::AUTO_REWRITE_AND_TRANSFER:
                $actionEquivalent = 'FullAutomation';
                break;
            default:
                $actionEquivalent = $action;
                break;
        }
        $pipelineId = $pipeline['id'];
        $keywords = $pipeline['keywords'];
        foreach ($difficulties as $difficulty) {
            if (isset($keywords[$difficulty])) {
                $triggerSettings[$difficulty] = [
                    'option' => $optionEquivalent,
                    'value' => $value,
                    'action' => $actionEquivalent,
                    'textTypes' => $textTypes ?? []
                ];
            }
        }
        return $triggerSettings;
    }

    /**
     * Delete ranking keywords
     *
     * @param string $storeId
     * @param string $recordId
     * @param string $type
     * @param array $keywordsToRemove
     *
     * @return array
     */
    public function deleteRankingKeywords(
        $storeId,
        $recordId,
        $type,
        $keywordsToRemove
    ) {
        try {
            $storeLanguage =  $this->storeHelper->getFormattedLanguage($storeId);
            $body = [
                "storeId" => $storeId,
                "type" => $type,
                "recordId" => $recordId,
                "languageCode" => $storeLanguage,
                "keywords" => $keywordsToRemove
            ];

            $response = $this->curlBuilder->getApiResponseCustom(
                'text/Keywords/Optimization/RankingKeywords',
                $body,
                'delete'
            );
        } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
            if ($e->getCode() === 404) {
                $response = [];
            } else {
                throw $e;
            }
        }
        return $response;
    }
}
