<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Cache\CacheManager as Cache;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Http\Request;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Routing\Middleware\ValidateSignature as BaseMiddleware;
use Illuminate\Support\Carbon;

/**
 * Class ValidateSignature
 */
class ValidateSignature extends BaseMiddleware
{
    /**
     * Cache manager
     */
    protected Repository $cacheDriver;

    /**
     * Create a new ValidateSignature instance.
     */
    public function __construct(Cache $cache)
    {
        $this->cacheDriver = $cache->driver(config('cache.default'));
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $consume
     * @return \Illuminate\Http\Response
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle($request, Closure $next, $consume = false)
    {
        if (($consume && $this->signatureConsumed($request)) || ! $request->hasValidSignature()) {
            throw new InvalidSignatureException;
        }

        /** @var \Illuminate\Http\Response $response */
        $response = $next($request);

        if ($consume && $response->isSuccessful()) {
            $this->consumeSignature($request);
        }

        return $response;
    }

    /**
     * Checks if the signature was consumed
     *
     *
     * @return bool
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function signatureConsumed(Request $request)
    {
        return $this->cacheDriver->has($this->cacheKey($request));
    }

    /**
     * Consumes the signature, marking it as unavailable
     *
     *
     * @return void
     */
    protected function consumeSignature(Request $request)
    {
        $ttl = Carbon::createFromTimestamp($request->query('expires'));

        $this->cacheDriver->put($this->cacheKey($request), null, $ttl);
    }

    /**
     * Return the cache Key to check
     *
     *
     * @return string
     */
    protected function cacheKey(Request $request)
    {
        return 'consumable|'.$request->query('signature');
    }
}
