<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */
declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Plugin\Config;

use Magento\Config\Model\Config\Structure\Data;
use Magento\Backend\Model\Auth\Session as AdminSession;
use WriteTextAI\WriteTextAI\Helper\Data as Helper;
use WriteTextAI\WriteTextAI\Exception\UnauthorizedException;

class RemoveSectionFromData
{
    /**
     * @var Helper
     */
    private Helper $helper;
    /**
     * @var AdminSession
     */
    private AdminSession $adminSession;

    /**
     * @param Helper $helper
     * @param AdminSession $adminSession
     */
    public function __construct(
        Helper $helper,
        AdminSession $adminSession
    ) {
        $this->helper = $helper;
        $this->adminSession = $adminSession;
    }
    /**
     * Remove the WriteTextAI section from the config
     *
     * @param Data $subject
     * @param array $config
     * @return array
     */
    public function afterGet(Data $subject, array $config): array
    {
        if ($this->isSetupComplete()) {
            return $config;
        }

        $sectionId = Helper::SECTION_NAME;

        if (isset($config['sections'][$sectionId])) {
            unset($config['sections'][$sectionId]);
        }

        return $config;
    }

    /**
     * Check if the setup is complete
     *
     * @return bool
     */
    private function isSetupComplete(): bool
    {
        try {
            return $this->adminSession->isLoggedIn()
                && $this->helper->isDataMapped()
                && $this->helper->isSetupFinalized();
        } catch (UnauthorizedException $e) {
            return false;
        }
    }
}
