<?php

namespace Autogedal\TbiBank\Plugin;

use Autogedal\TbiBank\Model\Environment;
use Magento\Config\Model\ResourceModel\Config;
use Magento\Framework\Event\Observer;
use TbiBank\FusionPay\Observer\AfterConfigSave;

class SettingsSync
{
    private Environment $environment;
    private bool $synchronizing = false;

    public function __construct(Environment $environment)
    {
        $this->environment = $environment;
    }

    public function aroundExecute(AfterConfigSave $subject, callable $proceed, Observer $observer)
    {
        $previous = $this->synchronizing;
        $this->synchronizing = true;
        try {
            return $proceed($observer);
        } finally {
            $this->synchronizing = $previous;
        }
    }

    public function beforeSaveConfig(Config $subject, $path, $value, $scope = 'default', $scopeId = 0): array
    {
        if ($this->synchronizing && $this->environment->isUat()) {
            $effectivePath = $this->environment->getEffectivePath((string) $path);
            if ($effectivePath !== $path) {
                return [$effectivePath, $value, 'default', 0];
            }
        }
        return [$path, $value, $scope, $scopeId];
    }
}
