<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Wechat\V2\Pay\Pos;

use Closure;
use Throwable;
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\XmlPacker;
use Kylin\Pay\Artful\Rocket;
use Kylin\Pay\Supports\Str;

use function Kylin\Pay\get_provider_config;
use function Kylin\Pay\get_wechat_type_key;

/**
 * @see https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_10&index=1
 */
class PayPlugin implements PluginInterface
{
    /**
     * @throws ContainerException
     * @throws ServiceNotFoundException
     * @throws Throwable                随机字符串生成失败
     */
    public function assembly(Rocket $rocket, Closure $next): Rocket
    {
        Logger::debug('[Wechat][V2][Pay][Pos][PayPlugin] 插件开始装载', ['rocket' => $rocket]);

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

        $rocket->setPacker(XmlPacker::class)
            ->mergePayload([
                '_url' => 'pay/micropay',
                '_content_type' => 'application/xml',
                'appid' => $config[get_wechat_type_key($params)] ?? '',
                'mch_id' => $config['mch_id'] ?? '',
                'nonce_str' => Str::random(32),
                'sign_type' => 'MD5',
            ]);

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

        return $next($rocket);
    }
}
