<?php

/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

namespace Resursbank\MerchantApi\Service;

use PrestaShop\PrestaShop\Adapter\Configuration;
use Resursbank\MerchantApi\Config\Config;
use Resursbank\MerchantApi\Crypto\Openssl;
use Resursbank\MerchantApi\Exception\FakeContainerException;

class FakeContainer
{
    /**
     * Get Config object with DI.
     *
     * @throws FakeContainerException
     */
    public static function getConfig(): Config
    {
        return new Config(
            new Configuration(parameters: []),
            new Openssl(
                secret: self::getSecret()
            )
        );
    }

    /**
     * Extract the secret from the parameters.php file.
     */
    private static function getSecret(): string
    {
        $parametersFile = _PS_ROOT_DIR_ . '/app/config/parameters.php';

        if (!file_exists($parametersFile)) {
            throw new FakeContainerException('parameters.php file does not exist.');
        }

        $data = include $parametersFile;

        if (!is_array($data)) {
            throw new FakeContainerException('Invalid data in parameters.php');
        }

        if (!isset($data['parameters'])) {
            throw new FakeContainerException('Missing parameters in parameters.php');
        }

        if (!isset($data['parameters']['secret'])) {
            throw new FakeContainerException('Missing secret in parameters.php');
        }

        return (string) $data['parameters']['secret'];
    }
}
