<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Paypal\V2\Pay;

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

/**
 * @see https://developer.paypal.com/docs/api/orders/v2/#orders_capture
 */
class CapturePlugin implements PluginInterface
{
    /**
     * @throws InvalidParamsException
     */
    public function assembly(Rocket $rocket, Closure $next): Rocket
    {
        Logger::debug('[Paypal][V2][Pay][CapturePlugin] 插件开始装载', ['rocket' => $rocket]);

        $params = $rocket->getParams();
        $orderId = $params['order_id'] ?? '';

        if (empty($orderId)) {
            throw new InvalidParamsException(Exception::PARAMS_NECESSARY_PARAMS_MISSING, '参数异常: PayPal 订单捕获，缺少 order_id 参数');
        }

        $rocket->mergePayload([
            '_method' => 'POST',
            '_url' => 'v2/checkout/orders/'.$orderId.'/capture',
        ]);

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

        return $next($rocket);
    }
}
