<?php
declare(strict_types=1);

namespace Autogedal\Extend\Plugin\Security;

use Magento\Framework\Api\Data\ImageContentInterface;
use Magento\Framework\Api\ImageContentValidator;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Filesystem\Io\File as IoFile;
use Magento\Framework\Phrase;

/**
 * Blocks file uploads with non-image extensions via REST API (PolyShell / APSB25-94)
 */
class ImageContentValidatorPlugin
{
    private const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'gif', 'png'];

    private IoFile $ioFile;

    public function __construct(IoFile $ioFile)
    {
        $this->ioFile = $ioFile;
    }

    public function afterIsValid(
        ImageContentValidator $subject,
        bool $result,
        ImageContentInterface $imageContent
    ): bool {
        $pathInfo = $this->ioFile->getPathInfo($imageContent->getName());
        $extension = strtolower($pathInfo['extension'] ?? '');

        if ($extension && !in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
            throw new InputException(
                new Phrase('The image file extension "%1" is not allowed.', [$extension])
            );
        }

        return $result;
    }
}
