<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

/**
 * This middleware used in API only, to make sure that if frontend sent the requests twice with the same idempotency key,
 * the second request will return the response from the cache, not the actual response from the API
 */
class IdempotencyMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $idempotencyKey = $request->header('Idempotency-Key');
        if (!$idempotencyKey) {
            // No Idempotency-Key found , proceed to the next middleware function
            return $next($request);
        }

        // $request->method() = POST/GET/PUT/DELETE
        // $request->path() = api/page/2
        $cacheKey = 'idempotency:' . Str::slug($request->method() . '-' . $request->path()) . $idempotencyKey;
        // idempotency:get-apipage2request-idempotency-key
        $cachedResponse = Cache::get($cacheKey);
        if ($cachedResponse) {
            // get response from cache
            $cachedResponse = json_decode($cachedResponse, true);
            $cachedResponse['cached'] = true;
            return response()->json($cachedResponse);
        }
        $response = $next($request);

        // Cache the response for future requests with the same idempotency key
        $responseToSave = $response->getContent();
        Cache::put($cacheKey, $responseToSave, now()->addMinutes(1));
        return $response;
    }
}
