<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Stripe\V1;

use Closure;
use GuzzleHttp\Psr7\Request;
use Kylin\Pay\Artful\Contract\PluginInterface;
use Kylin\Pay\Artful\Exception\ContainerException;
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\Supports\Collection;

use function Kylin\Pay\Artful\filter_params;
use function Kylin\Pay\Artful\get_radar_method;
use function Kylin\Pay\get_provider_config;
use function Kylin\Pay\get_stripe_url;

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

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

        $rocket->setRadar(new Request(
            get_radar_method($payload),
            get_stripe_url($config, $payload).$this->getQueryString($payload),
            $this->getHeaders($config, $payload),
            $this->getBody($payload),
        ));

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

        return $next($rocket);
    }

    protected function getHeaders(array $config, ?Collection $payload): array
    {
        $secretKey = $config['secret_key'] ?? '';

        $headers = [
            'User-Agent' => 'yansongda/pay-v3',
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.$secretKey,
        ];

        $method = strtoupper($payload?->get('_method') ?? 'GET');

        if ('GET' !== $method) {
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
        }

        return $headers;
    }

    protected function getBody(?Collection $payload): string
    {
        $method = strtoupper($payload?->get('_method') ?? 'GET');

        if ('GET' === $method) {
            return '';
        }

        return http_build_query(filter_params($payload)->toArray());
    }

    protected function getQueryString(?Collection $payload): string
    {
        $method = strtoupper($payload?->get('_method') ?? 'GET');

        if ('GET' !== $method) {
            return '';
        }

        $params = filter_params($payload)->toArray();

        return empty($params) ? '' : '?'.http_build_query($params);
    }
}
