<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Cron;

use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Daily cron to sync switchInfo (isChecked) from SimplyIN API
 *
 * - API isChecked=true  → admin checkbox value=0, field enabled (merchant can change)
 * - API isChecked=false → admin checkbox value=0, field disabled (locked by SimplyIN)
 */
class SyncSwitchInfo
{
    private const CONFIG_PATH_API_KEY = 'payment/simplyin_payment/api_key';
    private const CONFIG_PATH_DEFAULT_CHECKED = 'payment/simplyin_payment/default_create_account_checked';
    private const CONFIG_PATH_DEFAULT_CHECKED_DISABLED = 'payment/simplyin_payment/default_create_account_checked_disabled';

    /**
     * @var WriterInterface
     */
    private WriterInterface $configWriter;

    /**
     * @var ScopeConfigInterface
     */
    private ScopeConfigInterface $scopeConfig;

    /**
     * @var ApiClient
     */
    private ApiClient $apiClient;

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * @param WriterInterface $configWriter
     * @param ScopeConfigInterface $scopeConfig
     * @param ApiClient $apiClient
     * @param LoggerInterface $logger
     */
    public function __construct(
        WriterInterface $configWriter,
        ScopeConfigInterface $scopeConfig,
        ApiClient $apiClient,
        LoggerInterface $logger
    ) {
        $this->configWriter = $configWriter;
        $this->scopeConfig = $scopeConfig;
        $this->apiClient = $apiClient;
        $this->logger = $logger;
    }

    /**
     * Sync switchInfo (isChecked) from the SimplyIN API into store config.
     *
     * @return void
     */
    public function execute(): void
    {
        $apiKey = $this->scopeConfig->getValue(self::CONFIG_PATH_API_KEY, ScopeInterface::SCOPE_STORE);
        if (empty($apiKey)) {
            return;
        }

        try {
            $response = $this->apiClient->getPluginSyncInfo();

            if (!$response['success'] || empty($response['data'])) {
                $this->logger->warning('SimplyIN SyncSwitchInfo: Failed to fetch plugin sync info');
                return;
            }

            $data = $response['data'];

            if (!isset($data['switchInfo']['isChecked'])) {
                return;
            }

            $apiIsChecked = (bool)$data['switchInfo']['isChecked'];

            if ($apiIsChecked) {
                // API isChecked=true → field enabled, merchant can change the value
                $this->configWriter->save(self::CONFIG_PATH_DEFAULT_CHECKED_DISABLED, '0', ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0);
                $this->logger->info('SimplyIN SyncSwitchInfo: isChecked=true → field enabled');
            } else {
                // API isChecked=false → force value to 0, field disabled
                $this->configWriter->save(self::CONFIG_PATH_DEFAULT_CHECKED, '0', ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0);
                $this->configWriter->save(self::CONFIG_PATH_DEFAULT_CHECKED_DISABLED, '1', ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0);
                $this->logger->info('SimplyIN SyncSwitchInfo: isChecked=false → value reset, field disabled');
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN SyncSwitchInfo: Error', ['error' => $e->getMessage()]);
        }
    }
}
