<?php

declare(strict_types=1);

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

namespace Amasty\ImageOptimizer\Plugin\MediaGalleryRenditions\Model\GenerateRenditions;

use Amasty\ImageOptimizer\Model\ImageProcessor\AutoProcessing\ProcessorsProvider;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\MediaGalleryRenditions\Model\GenerateRenditions;
use Magento\MediaGalleryRenditionsApi\Api\GetRenditionPathInterface;

class CreateWebpAfterCopy
{
    /**
     * @var WriteInterface
     */
    private WriteInterface $mediaDirectory;

    public function __construct(
        private readonly ProcessorsProvider $processorsProvider,
        private readonly GetRenditionPathInterface $getRenditionPath,
        Filesystem $filesystem,
    ) {
        $this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
    }

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @param null $result
     *
     * @throws LocalizedException
     */
    public function afterExecute(
        GenerateRenditions $subject,
        $result,
        array $paths
    ): void {
        foreach ($paths as $path) {
            if (!$this->mediaDirectory->isFile($path)) {
                continue;
            }

            $renditionPath = $this->getRenditionPath->execute($path);
            if (!$this->mediaDirectory->isExist($renditionPath)
                || !$this->mediaDirectory->isFile($renditionPath)
            ) {
                continue;
            }

            foreach ($this->processorsProvider->getAll() as $processor) {
                $processor->execute($renditionPath);
            }
        }
    }
}
