<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Paypal\V2;

use Closure;
use Kylin\Pay\Artful\Contract\PluginInterface;
use Kylin\Pay\Artful\Exception\ContainerException;
use Kylin\Pay\Artful\Exception\InvalidConfigException;
use Kylin\Pay\Artful\Exception\InvalidParamsException;
use Kylin\Pay\Artful\Exception\ServiceNotFoundException;
use Kylin\Pay\Artful\Logger;
use Kylin\Pay\Artful\Rocket;

use function Kylin\Pay\get_paypal_access_token;

class ObtainAccessTokenPlugin implements PluginInterface
{
    /**
     * @throws ContainerException
     * @throws InvalidConfigException
     * @throws InvalidParamsException
     * @throws ServiceNotFoundException
     */
    public function assembly(Rocket $rocket, Closure $next): Rocket
    {
        Logger::debug('[Paypal][V2][ObtainAccessTokenPlugin] 插件开始装载', ['rocket' => $rocket]);

        $params = $rocket->getParams();

        $token = $params['_access_token'] ?? '';

        if (empty($token)) {
            $token = get_paypal_access_token($params);
        }

        $rocket->mergePayload(['_access_token' => $token]);

        Logger::info('[Paypal][V2][ObtainAccessTokenPlugin] 插件装载完毕', ['rocket' => $rocket]);

        return $next($rocket);
    }
}
