<?php
namespace Mefi\YtModule\MefisAssetBridge\Listener;

use YOOtheme\Config;
use YOOtheme\Metadata;
use YOOtheme\Path;

class LoadMefisAssetBridgeConfigData
{
    public Config $config;
    public Metadata $metadata;

    public function __construct(Config $config, Metadata $metadata)
    {
        $this->config   = $config;
        $this->metadata = $metadata;
    }
    public function handle(): void
    {
        $this->config->addFile('customizer', Path::get('../config/customizer.json'));

        // use .min if exist
        $baseAlias  = '~mefisassetbridgemedia/js/mefis-asset-bridge-v2';
        $minAlias   = $baseAlias . '.min.js';
        $plainAlias = $baseAlias . '.js';

        $minPath   = Path::get($minAlias);
        $plainPath = Path::get($plainAlias);

        if ($minPath && is_file($minPath)) {
            $src = $minAlias;
        } elseif ($plainPath && is_file($plainPath)) {
            $src = $plainAlias;
        } else {
            $src = $plainAlias;
        }

        $this->metadata->set('script:mefisassetbridgemedia-js', [
            'src'   => $src,
            'defer' => true,
        ]);
    }
}
