<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Controller\Adminhtml\Shipment;

use Macopedia\OrlenShipping\Model\Api\OrlenApiException;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Macopedia\OrlenShipping\Model\Api\Pickup as ApiPickup;

class AvailablePickups extends Action
{
    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    public const ADMIN_RESOURCE = 'Magento_Sales::shipment';

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param ApiPickup $apiPickup
     */
    public function __construct(
        Context $context,
        private readonly JsonFactory $resultJsonFactory,
        private readonly ApiPickup $apiPickup
    ) {
        parent::__construct($context);
    }

    /**
     * Get available pickup windows for shipments
     *
     * @return ResultInterface
     */
    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();
        try {
            $pickupWindows = $this->apiPickup->getAvailableWindows();
            return $resultJson->setData([
                'success' => true,
                'dates' => $pickupWindows
            ]);
        } catch (\Exception $e) {
            return $resultJson->setData([
                'success' => false,
                'message' => __('An error occurred.<br>%1', $e->getMessage())
            ]);
        }
    }
}
