<?php

namespace App\Http\Middleware;

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

class CanonicalPathMiddleware
{
    /**
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $rawPath = parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
        $rawPath = is_string($rawPath) && $rawPath !== '' ? $rawPath : null;
        $path = $rawPath ?? '/'.ltrim($request->path(), '/');

        if ($path !== '/' && str_ends_with($path, '/')) {
            $canonicalPath = rtrim($path, '/');
            $query = $request->getQueryString();
            if ($query !== null && $query !== '') {
                $canonicalPath .= '?'.$query;
            }

            return new RedirectResponse($canonicalPath, 301);
        }

        return $next($request);
    }
}
