<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Controller\Adminhtml\Config;

use Exception;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Macopedia\OrlenShipping\Model\Api\GivePartnerStatus;
use Macopedia\OrlenShipping\Model\Api\Ping;

class TestConnection extends Action
{
    /**
     * @param Context $context
     * @param GivePartnerStatus $givePartnerStatus
     * @param Ping $ping
     */
    public function __construct(
        Context $context,
        private readonly GivePartnerStatus $givePartnerStatus,
        private readonly Ping $ping
    ) {
        parent::__construct($context);
    }

    /**
     * Test connection
     *
     * @return ResponseInterface|ResultInterface
     */
    public function execute(): ResultInterface|ResponseInterface
    {
        try {
            $result = [
                'status'  => true,
                'content' => __(
                    'API ORLEN Paczka connection is working properly.<br>PartnerID and PartnerKey are correct.'
                )
            ];

            $partnerId = trim($this->getRequest()->getParam('partnerId'));
            $partnerKey = trim($this->getRequest()->getParam('partnerKey'));

            $pingResponse = $this->ping->ping();
            if ($pingResponse->PingStatus) {
                try {
                    $this->givePartnerStatus->getData($partnerId, $partnerKey);
                } catch (Exception $e) {
                    $result = [
                        'status'  => false,
                        'content' => __('An error occurred while trying to connect.<br>%1', $e->getMessage())
                    ];
                }
            } else {
                $result = [
                    'status'  => false,
                    'content' => __('API ORLEN Paczka does not respond at the moment. Try again later.')
                ];
            }
        } catch (Exception $e) {
            $result = [
                'status'  => false,
                'content' => __('An error occurred.<br>%1', $e->getMessage())
            ];
        }

        return $this->getResponse()->representJson(json_encode($result));
    }
}
