<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Jsb;

use Closure;
use Kylin\Pay\Artful\Contract\PluginInterface;
use Kylin\Pay\Artful\Exception\ContainerException;
use Kylin\Pay\Artful\Exception\ServiceNotFoundException;
use Kylin\Pay\Artful\Logger;
use Kylin\Pay\Artful\Packer\QueryPacker;
use Kylin\Pay\Artful\Rocket;
use Kylin\Pay\Supports\Str;

use function Kylin\Pay\get_provider_config;

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

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

        $rocket->setPacker(QueryPacker::class)
            ->mergePayload(array_merge($params, [
                'createData' => date('Ymd'),
                'createTime' => date('His'),
                'bizDate' => date('Ymd'),
                'msgId' => Str::uuidV4(),
                'svrCode' => $config['svr_code'] ?? '',
                'partnerId' => $config['partner_id'] ?? '',
                'channelNo' => 'm',
                'publicKeyCode' => $config['public_key_code'] ?? '',
                'version' => 'v1.0.0',
                'charset' => 'utf-8',
            ]));

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

        return $next($rocket);
    }
}
