<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Alipay\V2;

use Closure;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
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\Rocket;
use Kylin\Pay\Supports\Collection;

use function Kylin\Pay\Artful\get_radar_method;
use function Kylin\Pay\get_alipay_url;
use function Kylin\Pay\get_provider_config;

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

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

        $rocket->setRadar(new Request(
            // 这里因为支付宝的 payload 里不包含 _method，所以需要取 params 中的
            get_radar_method(new Collection($params)) ?? 'POST',
            get_alipay_url($config, $payload),
            $this->getHeaders($params),
            // 不能用 artful 中 get_radar_body 方法
            // 来自 AddPayloadBodyPlugin 插件通过 packer 生成的 _body
            // 支付宝接收的是 x-www-form-urlencoded 返回的又是 json，packer 用的是返回.
            $this->getBody($payload, $params)
        ));

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

        return $next($rocket);
    }

    protected function getHeaders(array $params): array
    {
        if (!empty($params['_multipart'])) {
            return [];
        }

        return [
            'Content-Type' => 'application/x-www-form-urlencoded',
            'User-Agent' => 'yansongda/pay-v3',
        ];
    }

    protected function getBody(?Collection $payload, array $params): MultipartStream|string
    {
        if (!empty($params['_multipart'])) {
            $multipartData = $params['_multipart'];
            foreach ($payload as $name => $value) {
                $multipartData[] = [
                    'name' => $name,
                    'contents' => $value,
                ];
            }

            return new MultipartStream($multipartData, uniqid('alipay_', true));
        }

        return $payload?->query() ?? '';
    }
}
