<?php

namespace App\Http\Middleware;

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

class ValidateGatewayToken
{
    /**
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $configuredToken = (string) config('gateway.token', '');

        if ($configuredToken === '') {
            return new JsonResponse([
                'message' => 'The SMS gateway API token is not configured.',
            ], Response::HTTP_SERVICE_UNAVAILABLE);
        }

        $providedToken = $request->bearerToken() ?: $request->header('X-Gateway-Token', '');

        if (! is_string($providedToken) || ! hash_equals($configuredToken, $providedToken)) {
            return new JsonResponse([
                'message' => 'Invalid SMS gateway token.',
            ], Response::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }
}
