<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Encryption;

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

final class Crypto implements CryptoInterface
{
    /**
     * @var \PhpEncryption
     */
    private $handler;

    public function __construct(\PhpEncryption $handler = null)
    {
        assert(defined('_NEW_COOKIE_KEY_'));
        $this->handler = $handler ?? new \PhpEncryption(_NEW_COOKIE_KEY_);
    }

    public function encrypt(string $plaintext): string
    {
        return $this->handler->encrypt($plaintext);
    }

    public function decrypt(string $ciphertext): string
    {
        if (false !== $plaintext = $this->handler->decrypt($ciphertext)) {
            return $plaintext;
        }

        throw new \RuntimeException('Could not decrypt the ciphertext.');
    }
}
