<?php

declare(strict_types=1);

namespace Tricks\LaravelTools\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

final class CompressMiddleware
{
    public function handle(Request $request, Closure $next): mixed
    {
        $response = $next($request);

        if (in_array('gzip', $request->getEncodings()) === false) {
            return $response;
        }
        if (
            ($response instanceof Response === false)
            && ($response instanceof JsonResponse === false)
            && ($response instanceof RedirectResponse === false)
        ) {
            return $response;
        }
        if ($response->headers->get('Content-Encoding') === 'gzip') {
            return $response;
        }

        $response->header('Content-Encoding', 'gzip');
        $response->header('Vary', 'Accept-Encoding');
        $response->setContent(gzencode($response->content(), 9));

        return $response;
    }
}
