<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\FormActivity;
use Symfony\Component\HttpFoundation\Response;

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

        $formId = $request->input('id');
        if ($formId) {
            match ($response->getStatusCode()) {
                200 => FormActivity::recordSuccess($formId),
                422 => FormActivity::recordValidationError($formId),
                default => FormActivity::recordFailure($formId),
            };
        }

        return $response;
    }
}
