<?php

declare(strict_types=1);

namespace Kylin\Pay\Plugin\Wechat\V3\Marketing\Coupon\Callback;

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

/**
 * @see https://pay.weixin.qq.com/docs/merchant/apis/cash-coupons/call-back-url/query-callback.html
 * @see https://pay.weixin.qq.com/docs/partner/apis/cash-coupons/call-back-url/query-callback.html
 */
class QueryPlugin implements PluginInterface
{
    /**
     * @throws ContainerException
     * @throws ServiceNotFoundException
     */
    public function assembly(Rocket $rocket, Closure $next): Rocket
    {
        Logger::debug('[Wechat][Marketing][Coupon][Callback][QueryPlugin] 插件开始装载', ['rocket' => $rocket]);

        $params = $rocket->getParams();
        $config = get_provider_config('wechat', $params);
        $mchId = $rocket->getPayload()?->get('mchid') ?? $config['mch_id'] ?? 'null';

        $rocket->setPayload([
            '_method' => 'GET',
            '_url' => 'v3/marketing/favor/callbacks?mchid='.$mchId,
            '_service_url' => 'v3/marketing/favor/callbacks?mchid='.$mchId,
        ]);

        Logger::info('[Wechat][Marketing][Coupon][Callback][QueryPlugin] 插件装载完毕', ['rocket' => $rocket]);

        return $next($rocket);
    }
}
