<?php

namespace Kylin\Payment\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Kylin\Payment\Payment;

/**
 * 支付回调中间件
 */
class PaymentCallbackMiddleware
{
    /**
     * 处理请求
     */
    public function handle(Request $request, Closure $next, ?string $paymentType = null, string $configName = 'default'): mixed
    {
        // 验证支付类型
        if (empty($paymentType)) {
            return response()->json([
                'code' => 400,
                'message' => '支付类型不能为空',
            ], 400);
        }

        // 获取请求数据
        $data = $request->all();

        // 验证IP白名单
        if (!Payment::security()->verifyIpWhitelist($paymentType, $request->ip(), $configName)) {
            return response()->json([
                'code' => 403,
                'message' => 'IP地址不在白名单中',
            ], 403);
        }

        // 验证签名
        $signature = $this->getSignature($request, $paymentType);
        if (!Payment::security()->verifySignature($paymentType, $data, $signature, $configName)) {
            return response()->json([
                'code' => 401,
                'message' => '签名验证失败',
            ], 401);
        }

        // 将支付类型和配置名称添加到请求中
        $request->merge([
            'payment_type' => $paymentType,
            'config_name' => $configName,
        ]);

        return $next($request);
    }

    /**
     * 获取签名
     */
    protected function getSignature(Request $request, string $paymentType): ?string
    {
        // 根据支付类型获取签名
        return match ($paymentType) {
            'wechat', 'alipay', 'douyin', 'alipay_global' => $request->input('sign'),
            'unionpay', 'jsbank', 'google_pay', 'apple_pay' => $request->input('signature'),
            'paypal' => $request->header('PayPal-Signature'),
            'stripe' => $request->header('Stripe-Signature'),
            default => null,
        };
    }
}
