<?php

namespace App\Http\Middleware;

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

class VerifyWebhookSecret
{
    /**
     * Verify the incoming webhook request has a valid Bearer token.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $secret = config('services.mailops.webhook_secret');

        if (empty($secret)) {
            return response()->json(['error' => 'Webhook secret not configured'], 500);
        }

        $token = $request->bearerToken();

        if (! $token || ! hash_equals($secret, $token)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $next($request);
    }
}
