<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Plugin\Framework\DB\Adapter\Pdo;

use Amasty\JetTheme\Model\AssetManager;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Magento\Framework\DB\Adapter\Pdo\Mysql;
use Magento\Framework\Setup\SchemaListener;
use Psr\Log\LoggerInterface;

class GenerateThemeAsset
{
    /**
     * @var AssetManager
     */
    private $assetManager;

    /**
     * @var State
     */
    private $state;

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

    public function __construct(
        AssetManager $assetsManager,
        State $state,
        LoggerInterface $logger
    ) {
        $this->assetManager = $assetsManager;
        $this->state = $state;
        $this->logger = $logger;
    }

    /**
     * @param Mysql $subject
     * @param SchemaListener $result
     * @return SchemaListener
     */
    public function afterGetSchemaListener(Mysql $subject, SchemaListener $result): SchemaListener
    {
        try {
            $this->state->emulateAreaCode(
                Area::AREA_FRONTEND,
                [$this->assetManager, 'generate']
            );
        } catch (\Exception $e) {
            $this->logger->critical($e);
        }

        return $result;
    }
}
