<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Stripe\V1\Pay;

use Closure;
use Psr\Http\Message\ServerRequestInterface;
use Kylin\Pay\Artful\Contract\PluginInterface;
use Kylin\Pay\Artful\Direction\NoHttpRequestDirection;
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 Kylin\Pay\Exception\Exception;
use Kylin\Pay\Exception\InvalidSignException;
use Kylin\Pay\Supports\Collection;

use function Kylin\Pay\verify_stripe_webhook_sign;

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

        $this->init($rocket);

        /* @phpstan-ignore-next-line */
        verify_stripe_webhook_sign($rocket->getDestinationOrigin(), $rocket->getParams());

        $bodyString = (string) $rocket->getDestination()->getBody();
        $body = json_decode($bodyString, true);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new InvalidParamsException(Exception::PARAMS_STRIPE_BODY_INVALID, '参数异常: Stripe 回调 body 不是合法 JSON');
        }

        $rocket->setDirection(NoHttpRequestDirection::class)
            ->setPayload(new Collection($body))
            ->setDestination(new Collection($body));

        Logger::info('[Stripe][V1][Pay][CallbackPlugin] 插件装载完毕', ['rocket' => $rocket]);

        return $next($rocket);
    }

    /**
     * @throws InvalidParamsException
     */
    protected function init(Rocket $rocket): void
    {
        $request = $rocket->getParams()['_request'] ?? null;
        $params = $rocket->getParams()['_params'] ?? [];

        if (!$request instanceof ServerRequestInterface) {
            throw new InvalidParamsException(Exception::PARAMS_CALLBACK_REQUEST_INVALID, '参数异常: Stripe 回调参数不正确');
        }

        $rocket->setDestination(clone $request)
            ->setDestinationOrigin($request)
            ->setParams($params);
    }
}
