<?php
namespace PortalPeople\DisabledPostcodes\Controller\Adminhtml\Postcode;

use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use PortalPeople\DisabledPostcodes\Model\Import\PostcodeImporter;

class Import extends AbstractPostcode
{
    public const ADMIN_RESOURCE = 'PortalPeople_DisabledPostcodes::import';

    private UploaderFactory $uploaderFactory;
    private Filesystem $filesystem;
    private PostcodeImporter $postcodeImporter;

    public function __construct(
        Context $context,
        UploaderFactory $uploaderFactory,
        Filesystem $filesystem,
        PostcodeImporter $postcodeImporter
    ) {
        parent::__construct($context);
        $this->uploaderFactory = $uploaderFactory;
        $this->filesystem = $filesystem;
        $this->postcodeImporter = $postcodeImporter;
    }

    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        try {
            $uploader = $this->uploaderFactory->create(['fileId' => 'import_file']);
            $uploader->setAllowedExtensions(['csv', 'xlsx']);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(false);

            $mediaDir = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
            $target = 'portalpeople/disabledpostcodes/import';
            $mediaDir->create($target);
            $result = $uploader->save($mediaDir->getAbsolutePath($target));

            if (!$result || empty($result['path']) || empty($result['file'])) {
                throw new \RuntimeException('Unable to save import file.');
            }

            $storeId = (int)$this->getRequest()->getParam('store_id', 0);
            $fullPath = rtrim($result['path'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($result['file'], DIRECTORY_SEPARATOR);
            $stats = $this->postcodeImporter->import($fullPath, (string)$result['name'], $storeId);

            $this->messageManager->addSuccessMessage(
                __('Import complete. Created: %1, Updated: %2, Skipped: %3.', $stats['created'], $stats['updated'], $stats['skipped'])
            );
        } catch (\Throwable $e) {
            $this->messageManager->addErrorMessage(__('Import failed: %1', $e->getMessage()));
        }

        return $resultRedirect->setPath('disabledpostcodes/postcode/index');
    }
}
