<?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\Model\Config\Backend;

use Magento\Config\Model\Config\Backend\Image as BackendImage;
use Magento\Framework\Exception\LocalizedException;

class Image extends BackendImage
{
    public const MAX_FILE_SIZE_KB = 2048;

    /**
     * @return Image
     * @throws LocalizedException
     */
    public function beforeSave()
    {
        $this->validateMaxFileSize();

        return parent::beforeSave();
    }

    /**
     * @throws LocalizedException
     */
    private function validateMaxFileSize(): void
    {
        $error = $this->getErrorParam();
        $fileData = $this->getValue();
        if (!is_array($fileData) || !isset($fileData['size'])) {
            return;
        }

        $fileSize = (int)$fileData['size'];
        if ($error === 1 || $fileSize && $fileSize / 1000 > self::MAX_FILE_SIZE_KB) {
            throw new LocalizedException(
                __('File you are trying to upload exceeds maximum file size limit.')
            );
        }
    }

    /**
     * @return int|null
     */
    private function getErrorParam(): ?int
    {
        return isset($this->getValue()['error']) ? (int)$this->getValue()['error'] : null;
    }
}
