<?php

namespace App\Http\Middleware;

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

class OptimizeResponse
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Only optimize successful GET requests that return HTML
        if ($request->isMethod('get') && $response->isSuccessful() && str_contains($response->headers->get('Content-Type'), 'text/html')) {
            $buffer = $response->getContent();

            if ($buffer !== false) {
                // Remove HTML comments
                $buffer = preg_replace('/<!--(.|\s)*?-->/', '', $buffer);

                // Collapse whitespace
                $search = [
                    '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
                    '/[^\S ]+\</s',     // strip whitespaces before tags, except space
                    '/(\s)+/s',         // shorten multiple whitespace sequences
                    '/^\s+|\s+$/m',      // trim each line
                ];
                $replace = ['>', '<', '\\1', ''];
                $buffer = preg_replace($search, $replace, $buffer);

                $response->setContent($buffer);
            }

            // Cloudflare/CDN Browser Cache Headers (1 hour for pages)
            if (!auth()->check()) {
                $response->headers->set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=600');
            }
        }

        return $response;
    }
}
