<?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\Client\Curl as MagentoCurl;
use WriteTextAI\WriteTextAI\Exception\VersionException;
use WriteTextAI\WriteTextAI\Logger\Logger;
use Magento\Framework\Message\ManagerInterface as MessageManager;

class VersionValidator
{
    /**
     * @var Logger
     */
    protected $logger;

    /**
     * @var MessageManager
     */
    protected $messageManager;

    /**
     * StatusCodeValidator constructor.
     *
     * @param Logger $logger
     * @param MessageManager $messageManager
     */
    public function __construct(
        Logger $logger,
        MessageManager $messageManager
    ) {
        $this->logger = $logger;
        $this->messageManager = $messageManager;
    }

    /**
     * Handle module version
     *
     * @param MagentoCurl $curl
     * @param string $moduleVersion
     * @param string $request
     * @param array $body
     *
     * @return void
     */
    public function validate($curl, $moduleVersion, $request, $body = [])
    {
        if ($this->isVersionError($curl->getBody())) {
            $error = $this->getErrorMessage($curl->getBody());
            $this->logger->logResponseErrors($error, $request, $body);
            $this->messageManager->getMessages(true);
            throw new VersionException(__($error));
        }

        if (!$this->isLatestVersion($curl, $moduleVersion)) {
            $headers = $curl->getHeaders();
            $message = $headers['WriteTextAI-PluginVersionMessage'] ?? '';
            $this->messageManager->getMessages(true);
            $this->messageManager->addNotice($message);
        }

        return true;
    }

    /**
     * Check if version is latest
     *
     * @param MagentoCurl $curl
     * @param string $moduleVersion
     * @return bool
     */
    public function isLatestVersion($curl, $moduleVersion): bool
    {
        $headers = $curl->getHeaders();

        if (isset($headers['WriteTextAI-LatestVersion'])
            && $headers['WriteTextAI-LatestVersion'] != $moduleVersion
        ) {
            return false;
        }

        return true;
    }

    /**
     * Check for version error
     *
     * @param string $body
     *
     * @return bool
     */
    protected function isVersionError($body): bool
    {
        $body = json_decode($body, true);

        return is_array($body)
            && isset($body['error'])
            && isset($body['code'])
            && $body['code'] == 22;
    }

    /**
     * Get the error message from the response
     *
     * @param string $curlBody
     * @return string
     */
    protected function getErrorMessage($curlBody = '')
    {
        try {
            $unserializedMessage = json_decode($curlBody, true);
            $error = $unserializedMessage['errors']
                ?? $unserializedMessage['error']
                ?? $curlBody;

            if (is_array($error) || is_object($error)) {
                $error = json_encode($error);
            }

            return $error;
        } catch (\InvalidArgumentException $e) {
            return $curlBody;
        }
    }
}
