<?php

namespace Autogedal\TbiBank\Controller\Failure;

use Autogedal\TbiBank\Model\CallbackStatusUpdate;
use Autogedal\TbiBank\Model\CallbackAudit;
use Autogedal\TbiBank\Model\FailureRedirect;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Psr\Log\LoggerInterface;
use TbiBank\FusionPay\Helper\Data as FusionPayHelper;

/** Renders the page used when TBI rejects the financing application. */
class Index extends Action implements HttpGetActionInterface
{
    public function __construct(
        Context $context,
        private ResultFactory $pageResultFactory,
        private FailureRedirect $failureRedirect,
        private CallbackStatusUpdate $callbackStatusUpdate,
        private FusionPayHelper $fusionPayHelper,
        private LoggerInterface $logger
    ) {
        parent::__construct($context);
    }

    /**
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $incrementId = trim((string) $this->getRequest()->getParam('order_id'));
        $signature = trim((string) $this->getRequest()->getParam('signature'));
        $encryptionKey = (string) $this->fusionPayHelper->getConfigValue(
            'tbi_settings/general_settings/encryption_key'
        );
        if ($this->failureRedirect->isValidSignature($incrementId, $signature, $encryptionKey)) {
            try {
                $this->callbackStatusUpdate->update(
                    $incrementId,
                    'Canceled',
                    null,
                    CallbackAudit::COMMAND_FAILURE_REDIRECT,
                    CallbackAudit::statusCodeFor('Canceled'),
                    null,
                    null
                );
            } catch (\Throwable $exception) {
                $this->logger->warning('TBI failure redirect could not update the order.', [
                    'increment_id' => $incrementId,
                    'exception' => $exception,
                ]);
            }
        }

        return $this->pageResultFactory->create(ResultFactory::TYPE_PAGE);
    }
}
