<?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\Configuration\Repository;

use InPost\International\Configuration\OrdersConfiguration;
use PrestaShop\PrestaShop\Core\Domain\Configuration\ShopConfigurationInterface;
use PrestaShop\PrestaShop\Core\Domain\Shop\ValueObject\ShopConstraint;

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

final class OrdersConfigurationRepository implements OrdersConfigurationRepositoryInterface
{
    private const LABEL_PRINTED_OS_ID_KEY = 'INPOST_INTL_LABEL_PRINTED_OS_ID';
    private const SHIPMENT_DELIVERED_OS_ID_KEY = 'INPOST_INTL_SHIPMENT_DELIVERED_OS_ID';

    /**
     * @var ShopConfigurationInterface
     */
    private $configuration;

    /**
     * @var array{orders?: OrdersConfiguration}
     */
    private $cache = [];

    public function __construct(ShopConfigurationInterface $configuration)
    {
        $this->configuration = $configuration;
    }

    public function getOrdersConfiguration(): OrdersConfiguration
    {
        if (array_key_exists('orders', $this->cache)) {
            return $this->cache['orders'];
        }

        return $this->cache['orders'] = new OrdersConfiguration(
            $this->getLabelPrintedStatusId(),
            $this->getShipmentDeliveredStatusId()
        );
    }

    public function saveOrdersConfiguration(OrdersConfiguration $configuration, ShopConstraint $shops = null): void
    {
        $this->setLabelPrintedStatusId($configuration->getLabelPrintedStatusId(), $shops);
        $this->setShipmentDeliveredStatusId($configuration->getShipmentDeliveredStatusId(), $shops);

        if (null === $shops) {
            $this->cache['orders'] = $configuration;
        } else {
            unset($this->cache['orders']);
        }
    }

    private function getLabelPrintedStatusId(): ?int
    {
        $value = $this->configuration->get(self::LABEL_PRINTED_OS_ID_KEY);

        return $value ? (int) $value : null;
    }

    private function setLabelPrintedStatusId(?int $value, ?ShopConstraint $shops): void
    {
        $this->configuration->set(self::LABEL_PRINTED_OS_ID_KEY, $value, $shops);
    }

    private function getShipmentDeliveredStatusId(): ?int
    {
        $value = $this->configuration->get(self::SHIPMENT_DELIVERED_OS_ID_KEY);

        return $value ? (int) $value : null;
    }

    private function setShipmentDeliveredStatusId(?int $value, ?ShopConstraint $shops): void
    {
        $this->configuration->set(self::SHIPMENT_DELIVERED_OS_ID_KEY, $value, $shops);
    }
}
