<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Paypal\V2;

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\get_radar_method;
use function Kylin\Pay\get_paypal_url;
use function Kylin\Pay\get_provider_config;

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

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

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

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

        return $next($rocket);
    }

    protected function getHeaders(array $config, ?Collection $payload): array
    {
        $headers = [
            'User-Agent' => 'yansongda/pay-v3',
            'Accept' => 'application/json',
        ];

        if ('basic' === $payload?->get('_auth_type')) {
            $clientId = $config['client_id'] ?? '';
            $appSecret = $config['app_secret'] ?? '';
            $headers['Authorization'] = 'Basic '.base64_encode($clientId.':'.$appSecret);
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
        } else {
            $token = $payload?->get('_access_token') ?? '';
            $headers['Authorization'] = 'Bearer '.$token;
            $headers['Content-Type'] = 'application/json; charset=utf-8';
        }

        return $headers;
    }

    protected function getBody(?Collection $payload): string
    {
        if ('basic' === $payload?->get('_auth_type')) {
            return 'grant_type=client_credentials';
        }

        return $payload?->get('_body') ?? '';
    }
}
