<?php

namespace App\Http\Middleware;

use App\Services\ApiResponseCache;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CacheApiResponse
{
    public function __construct(
        private readonly ApiResponseCache $apiResponseCache,
    ) {
    }

    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->isMethod('GET')) {
            return $next($request);
        }

        $routeName = $request->route()?->getName();
        $profile = $this->apiResponseCache->profileForRoute($routeName);

        if ($profile === null) {
            return $next($request);
        }

        $cacheKey = $this->apiResponseCache->buildKey($request, $routeName, $profile);
        $cachedPayload = $this->apiResponseCache->get($cacheKey);

        if ($cachedPayload !== null) {
            $response = $this->apiResponseCache->toResponse($cachedPayload);
            $response->headers->set('X-Response-Cache', 'HIT');

            return $response;
        }

        $response = $next($request);

        if ($this->apiResponseCache->put($cacheKey, $response, (int) $profile['ttl'])) {
            $response->headers->set('X-Response-Cache', 'MISS');
        }

        return $response;
    }
}
