<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  Joomla_System_Plugin
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Extension\PluginInterface;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\WebAsset\WebAssetRegistry;
use Joomla\DI\Container;
use Joomla\DI\ServiceProviderInterface;
use Joomla\Event\DispatcherInterface;
use Mefi\Plugin\System\MefisAssetBridge\MefisAssetBridge;

return new class implements ServiceProviderInterface {

    public function register(Container $container)
    {
        $container->set(
            PluginInterface::class,
            function (Container $container) {
                $app        = Factory::getApplication();

                // Toggle logging
                if (!defined('MEFIS_AB_DEBUG')) {
                    $cmsParams = \Joomla\CMS\Component\ComponentHelper::getParams('com_mefisassetbridge');
                    define('MEFIS_AB_DEBUG', (bool) $cmsParams->get('enable_log', false));
                }

                $corePath = JPATH_ADMINISTRATOR . '/components/com_mefisassetbridge/core/MefisAssetBridgeCore.php';
                if (!file_exists($corePath)) {
                    throw new \RuntimeException('MefisAssetBridgeCore not found at ' . $corePath);
                }

                require_once $corePath;


                $dispatcher = $container->get(DispatcherInterface::class);
                $plugin = new MefisAssetBridge(
                    $dispatcher,
                    (array) PluginHelper::getPlugin('system', 'mefisassetbridge'),
                    $app->isClient('administrator')
                );

                $wa = $container->get(WebAssetRegistry::class);

                $wa->addRegistryFile('media/plg_system_mefisassetbridge/joomla.asset.json');

                return $plugin;
            }
        );
    }

};