<?php

namespace Autogedal\TbiBank\Test\Unit;

use Autogedal\TbiBank\Model\ApprovalAccounting;
use Autogedal\TbiBank\Model\ApprovalConfig;
use Autogedal\TbiBank\Model\CallbackStatusUpdate;
use Autogedal\TbiBank\Plugin\GatewayCallback;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use TbiBank\FusionPay\Controller\Api\Gateway;
use TbiBank\FusionPay\Helper\Data as FusionPayHelper;
use TbiBank\FusionPay\Model\Cryptor;

class GatewayCallbackTest extends TestCase
{
    public function testDocumentedApprovalUsesStatusCodeEvenWhenLegacySourceConfigDiffers(): void
    {
        $request = $this->createPartialMock(Http::class, ['isPost', 'getContent']);
        $request->method('isPost')->willReturn(true);
        $request->method('getContent')->willReturn(json_encode([
            'data' => Cryptor::Encrypt(
                json_encode(['command' => 'update_status', 'OrderId' => 'AGD-123', 'Status' => '1']),
                'test-key'
            ),
        ]));

        $gateway = $this->createPartialMock(Gateway::class, ['getRequest']);
        $gateway->method('getRequest')->willReturn($request);

        $helper = $this->createMock(FusionPayHelper::class);
        $helper->expects($this->once())->method('getConfigValue')
            ->with('tbi_settings/general_settings/encryption_key')
            ->willReturn('test-key');

        $approvalConfig = $this->createMock(ApprovalConfig::class);
        $approvalConfig->expects($this->never())->method('getCallbackApprovedStatus');

        $accounting = $this->createMock(ApprovalAccounting::class);
        $accounting->expects($this->once())->method('approve')
            ->with('AGD-123', 'Approved', null, '1', null, null);

        $callbackStatusUpdate = $this->createMock(CallbackStatusUpdate::class);
        $callbackStatusUpdate->expects($this->never())->method('update');

        $jsonResult = $this->createMock(Json::class);
        $jsonResult->method('setData')->willReturnSelf();
        $jsonFactory = $this->createMock(JsonFactory::class);
        $jsonFactory->method('create')->willReturn($jsonResult);

        (new GatewayCallback(
            $helper,
            $approvalConfig,
            $accounting,
            $callbackStatusUpdate,
            $jsonFactory,
            $this->createMock(LoggerInterface::class)
        ))->aroundExecute($gateway, function (): void {
            $this->fail('The documented callback must be handled by the Autogedal plugin.');
        });
    }
}
