<?php

namespace HS\Http\Middleware;

use Closure;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class RequestGetsUniqueId
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $id = Str::uuid()->toString();

        $request->attributes->add(['request_id' => $id]);

        $response = $next($request);

        if ($response instanceof SymfonyResponse) {
            $response->headers->set('X-Helpspot-Request-Id', $id, true);
        }

        return $response;
    }
}
