<?php
declare(strict_types=1);

namespace Autogedal\PayPo\Plugin;

use Autogedal\PayPo\Model\PayPoContext;
use Magento\Framework\Controller\Result\Json;

class ApprovalResultPlugin
{
    public function __construct(private readonly PayPoContext $payPoContext)
    {
    }

    public function afterSetData(Json $subject, Json $result, mixed $data): Json
    {
        if ($this->payPoContext->isApprovingOrder()) {
            $this->payPoContext->setApprovalSucceeded(
                is_array($data) && (string)($data['code'] ?? '') === '200'
                && !isset($data['error_message'])
            );
        }

        return $result;
    }
}
