<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Alipay\V2;

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\ServiceNotFoundException;
use Kylin\Pay\Artful\Logger;
use Kylin\Pay\Artful\Rocket;
use Kylin\Pay\Exception\InvalidSignException;

use function Kylin\Pay\Artful\filter_params;
use function Kylin\Pay\get_provider_config;
use function Kylin\Pay\verify_alipay_sign;

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

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

        $value = filter_params($params, fn ($k, $v) => '' !== $v && 'sign' != $k && 'sign_type' != $k);

        verify_alipay_sign($config, $value->sortKeys()->toString(), $params['sign'] ?? '');

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

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

        return $next($rocket);
    }
}
