<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Service;

use Configuration;
use PrestaShopLogger;
use RuntimeException;
use SimplyIn\Api\ApiException;
use SimplyIn\Api\EncryptionService;
use SimplyIn\Api\SimplyInApiClient;

if (!defined('_PS_VERSION_')) {
    exit;
}

class EncryptedTrackingSender
{
    public function __construct(
        private readonly EncryptionService $encryption,
        private readonly SimplyInApiClient $apiClient,
    ) {
    }

    /**
     * @param array<string, mixed> $trackingNumber
     */
    public function send(
        string $orderEmail,
        string $orderReference,
        string $newOrderState,
        array $trackingNumber,
    ): false|string {
        $apiKey = (string) Configuration::get('SIMPLYIN_SECRET_KEY');
        $bodyData = [
            'email' => $orderEmail,
            'shopOrderNumber' => $orderReference,
            'newOrderStatus' => $newOrderState,
            'apiKey' => $apiKey,
            'trackings' => [$trackingNumber],
        ];

        $plaintext = json_encode($bodyData, JSON_UNESCAPED_SLASHES);
        if ($plaintext === false) {
            return false;
        }

        try {
            $encrypted = $this->encryption->encrypt($plaintext, $this->encryption->getSecretKey($orderEmail));
        } catch (RuntimeException $e) {
            PrestaShopLogger::addLog('SimplyIn: tracking encryption failed for order ' . $orderReference . ' (' . $e->getMessage() . ')', 3);

            return false;
        }

        $orderData = [
            'encryptedOrderStatusChangeContent' => $encrypted,
            'hashedEmail' => $this->encryption->getEmailHash($orderEmail),
        ];

        // Routed through the shared, RSA-wired SimplyInApiClient so this request is authenticated
        // and consistent with the rest of the plugin's runtime auth model.
        try {
            $response = $this->apiClient->request('POST', 'encryption/saveEncryptedOrderStatusChange', $orderData);
        } catch (ApiException $e) {
            PrestaShopLogger::addLog('SimplyIn: tracking push to Simply.IN failed for order ' . $orderReference . ' (' . $e->getMessage() . ')', 3);

            return false;
        }

        return $response->rawBody ?? '';
    }
}
