<?php

namespace App\Modules\Integrations\Platform\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

final class SetRequestCorrelationId
{
    public function handle(Request $request, Closure $next)
    {
        $incoming = (string) $request->headers->get('X-Request-Id', '');
        $rid = $incoming !== '' && strlen($incoming) <= 64 ? $incoming : (string) Str::uuid();

        $request->attributes->set('request_id', $rid);

        $response = $next($request);
        $response->headers->set('X-Request-Id', $rid);

        return $response;
    }
}

