<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SportCacheMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $path = $request->path();
        $maxAge = 604800;
        $response->headers->set('Cache-Control', 'public, max-age=' . $maxAge);
        if ($response->headers->get('Content-Type') && strpos($response->headers->get('Content-Type'), 'text/html') === false) {
            $etag = md5($path . '|' . ($response->headers->get('Content-Length') ?? ''));
            $response->headers->set('ETag', 'W/"' . $etag . '"');
            if ($request->headers->get('If-None-Match') === $response->headers->get('ETag')) {
                $response->setStatusCode(304);
                $response->setContent('');
            }
        }
        return $response;
    }
}