<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\ApiUsageEndpoint;
use Mtc\MercuryDataModels\Jobs\TrackApiRequest;
use Symfony\Component\HttpFoundation\Response;

class TrackRequests
{
    use DispatchesJobs;

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $start = microtime(true);
        $response =  $next($request);

        $request_length = microtime(true) - $start;
        $this->dispatch(new TrackApiRequest(
            tenant('id'),
            ApiUsageEndpoint::fromRequest($request),
            $request->input(),
            $request->method(),
            $response->getStatusCode(),
            $request_length
        ));

        /*
        This is not ready yet as we end up tracking multiple requests for single page load
        e.g. Homepage on hard-load calls get-site, pages/home and find-vehicle widget (twice)
        $this->dispatch(new TrackPageRequest(
            $request->header('X-Path'),
            $response->getStatusCode(),
            $request->route()->getName()
        ));
         */

        return $response;
    }
}
