<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Controller\Point;

use Macopedia\OrlenShipping\Helper\Data;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;

class Save extends Action
{
    /**
     * @param Context $context
     * @param Data $helper
     */
    public function __construct(
        Context $context,
        protected readonly Data $helper
    ) {
        parent::__construct($context);
    }

    /**
     * Execute action based on request and return result
     *
     * @return ResultInterface|ResponseInterface
     */
    public function execute(): ResultInterface|ResponseInterface
    {
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $description = $this->getRequest()->getParam('description');
        $destinationCode = $this->getRequest()->getParam('destination_code');
        try {
            if ($description && $destinationCode) {
                $this->helper->updateShippingMethod($description, $destinationCode);
                $resultJson->setData(['type' => 'success']);
            }
        } catch (\Exception $e) {
            $resultJson->setData(['type' => 'error', 'message' => $e->getMessage()]);
        }

        return $resultJson;
    }
}
