<?php
namespace Banyo\CustomProduct\Plugin;

use Mirasvit\Brand\Api\Data\BrandPageInterface;
use Mirasvit\Brand\Repository\BrandPageRepository;
use Magento\Framework\UrlInterface;

class BrandRepositoryPlugin
{
    /**
     * @var UrlInterface
     */
    private $urlBuilder;

    /**
     * @param UrlInterface $urlBuilder
     */
    public function __construct(
        UrlInterface $urlBuilder
    ) {
        $this->urlBuilder = $urlBuilder;
    }
    public function beforeSave(BrandPageRepository $subject, BrandPageInterface $brandPage)
    {
        $data = $brandPage->getData();

        if (isset($data['brand_product_page_logo'])) {
            if (is_array($data['brand_product_page_logo'])) {
                // Take first file name only (typical case for file uploader)
                $file = $data['brand_product_page_logo'][0]['name'] ?? null;
                $brandPage->setData('brand_product_page_logo', $file);
            } elseif (empty($data['brand_product_page_logo'])) {
                // If empty, set to null to avoid saving empty string
                $brandPage->setData('brand_product_page_logo', null);
            }
        }

        return [$brandPage];
    }

    public function afterGet(BrandPageRepository $subject, ?BrandPageInterface $brandPage)
    {
        if (!$brandPage) {
            return $brandPage;
        }

        $value = $brandPage->getData('brand_product_page_logo');

        // Only process if the value exists and is not already in the correct format
        if ($value) {
            // If it's already an array with the expected structure, leave it alone
            if (is_array($value) &&
                isset($value[0]['url']) &&
                isset($value[0]['name'])) {
                return $brandPage;
            }

            // If it's a string or an array without the expected structure, format it correctly
            $fileName = is_array($value) ? ($value[0]['name'] ?? '') : $value;

            if (!empty($fileName)) {
                $brandPage->setData('brand_product_page_logo', [
                    [
                        'name' => $fileName,
                        'url'  => $this->getMediaUrl($fileName),
                        'size' => $this->getFileSize($fileName), // Get actual file size if possible
                        'type' => $this->getMimeType($fileName), // Get actual MIME type if possible
                    ]
                ]);
            }
        }

        return $brandPage;
    }

    /**
     * Get the file size
     *
     * @param string $fileName
     * @return int
     */
    protected function getFileSize(string $fileName): int
    {
        $filePath = 'brand/logo/' . ltrim($fileName, '/');
        $mediaDirectory = \Magento\Framework\App\ObjectManager::getInstance()
            ->get(\Magento\Framework\Filesystem::class)
            ->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);

        if ($mediaDirectory->isExist($filePath)) {
            return $mediaDirectory->stat($filePath)['size'];
        }

        return 0;
    }

    /**
     * Get the MIME type of a file
     *
     * @param string $fileName
     * @return string
     */
    protected function getMimeType(string $fileName): string
    {
        $extension = pathinfo($fileName, PATHINFO_EXTENSION);

        $mimeTypes = [
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'svg' => 'image/svg+xml',
        ];

        return $mimeTypes[strtolower($extension)] ?? 'application/octet-stream';
    }

    protected function getMediaUrl(string $fileName): string
    {
        return $this->getBaseMediaUrl() . 'brand/logo/' . ltrim($fileName, '/');
    }

    protected function getBaseMediaUrl(): string
    {
        return rtrim(
                $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]),
                '/'
            ) . '/';
    }
}
