<?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\MailsConfiguration;
use PrestaShop\PrestaShop\Core\Domain\Configuration\ShopConfigurationInterface;
use PrestaShop\PrestaShop\Core\Domain\Shop\ValueObject\ShopConstraint;

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

final class MailsConfigurationRepository implements MailsConfigurationRepositoryInterface
{
    private const ORDER_CONFIRMATION_MAIL_KEY = 'INPOST_INTL_MODIFY_ORDER_CONF_MAIL';

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

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

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

    public function getMailsConfiguration(): MailsConfiguration
    {
        if (array_key_exists('mails', $this->cache)) {
            return $this->cache['mails'];
        }

        return $this->cache['mails'] = new MailsConfiguration(
            $this->getModifyOrderConfirmationMail()
        );
    }

    public function saveMailsConfiguration(MailsConfiguration $configuration, ShopConstraint $shops = null): void
    {
        $this->setModifyOrderConfirmationMail($configuration->modifyOrderConfirmation(), $shops);

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

    private function getModifyOrderConfirmationMail(): bool
    {
        return (bool) $this->configuration->get(self::ORDER_CONFIRMATION_MAIL_KEY);
    }

    private function setModifyOrderConfirmationMail(bool $value, ?ShopConstraint $shops): void
    {
        $this->configuration->set(self::ORDER_CONFIRMATION_MAIL_KEY, $value, $shops);
    }
}
