<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ValidatePaystackWebhook
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $payload = $request->getContent();
        $signature = $request->header('X-Paystack-Signature');

        if (!$signature) {
            return response()->json([
                'error' => true,
                'message' => 'Missing signature',
            ], 400);
        }

        $expectedSignature = hash_hmac('sha512', $payload, config('paystack.secret_key'));

        if (!hash_equals($expectedSignature, $signature)) {
            return response()->json([
                'error' => true,
                'message' => 'Invalid signature',
            ], 400);
        }

        return $next($request);
    }
}
