<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Jsb;

use Closure;
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\get_provider_config;
use function Kylin\Pay\verify_jsb_sign;

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

        $this->formatRequestAndParams($rocket);

        $params = $rocket->getParams();
        $config = get_provider_config('jsb', $params);

        $payload = $rocket->getPayload();
        $signature = $payload->get('sign');

        $payload->forget('sign');
        $payload->forget('signType');

        verify_jsb_sign($config, $payload->sortKeys()->toString(), $signature);

        $rocket->setDirection(NoHttpRequestDirection::class)
            ->setDestination($rocket->getPayload());

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

        return $next($rocket);
    }

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

        if (!$request instanceof Collection) {
            throw new InvalidParamsException(Exception::PARAMS_CALLBACK_REQUEST_INVALID);
        }

        $rocket->setPayload($request)->setParams($rocket->getParams()['params'] ?? []);
    }
}
