<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Controller\Adminhtml\Shipment;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Macopedia\OrlenShipping\Model\ProtocolFactory;
use Macopedia\OrlenShipping\Model\ResourceModel\Protocol as ProtocolResource;
use Macopedia\OrlenShipping\Helper\Data as Helper;
use Magento\Framework\Filesystem\Driver\File;

class DownloadProtocol extends Action
{
    /**
     * @param Context $context
     * @param FileFactory $fileFactory
     * @param ProtocolFactory $protocolFactory
     * @param ProtocolResource $protocolResource
     * @param Helper $helper
     * @param File $fileDriver
     */
    public function __construct(
        Action\Context $context,
        private readonly FileFactory $fileFactory,
        private readonly ProtocolFactory $protocolFactory,
        private readonly ProtocolResource $protocolResource,
        private readonly Helper $helper,
        private readonly File $fileDriver
    ) {
        parent::__construct($context);
    }

    /**
     * Controller execute action
     *
     * @return ResponseInterface|ResultInterface|void
     */
    public function execute()
    {
        $id = (int)$this->getRequest()->getParam('entity_id');
        try {
            $protocol = $this->protocolFactory->create();
            $this->protocolResource->load($protocol, $id);

            if (!$protocol->getId()) {
                throw new LocalizedException(__('Protocol not found.'));
            }

            $pdfName = $protocol->getData('file_name');
            $fileName = $this->helper->getShippingProtocolFolderPath() . $pdfName;
            if ($this->fileDriver->isExists($fileName)) {
                return $this->fileFactory->create(
                    $pdfName,
                    [
                        'type' => 'filename',
                        'value' => $fileName,
                        'rm' => false
                    ],
                    DirectoryList::VAR_DIR,
                    'application/pdf',
                    null
                );
            } else {
                throw new LocalizedException(__('Protocol not found.'));
            }
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(
                __('Failed to download protocol: %1', $e->getMessage())
            );
            return $this->_redirect($this->_redirect->getRefererUrl());
        }
    }
}
