<?php

namespace Velis\RateLimiter;

use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;
use Velis\App;
use Velis\Cache\CacheInterface;
use Velis\Http\Request;

/**
 * @author Szymon Janaczek <szymon.janaczek@singu.com>
 */
final class RateLimiterServiceProvider implements ServiceProviderInterface
{
    public function register(DiInterface $di): void
    {
        $di->set(LeakyBucketRateLimiterInterface::class, function (): LeakyBucketRateLimiterInterface {
            /** @var Request $request */
            $request = App::$di['request'];
            /** @var CacheInterface $cache */
            $cache = App::$di['cache'];

            $rateLimiter = new LeakyBucketRateLimiter($cache);

            $clientAddress = $request->getClientAddress();
            $rateLimiter->setIdentifier($clientAddress);

            return $rateLimiter;
        });

        $di->set(RateLimitRouteWrapperInterface::class, function () use ($di): RateLimitRouteWrapperInterface {
            /** @var LeakyBucketRateLimiterInterface $rateLimiter */
            $rateLimiter = $di->get(LeakyBucketRateLimiterInterface::class);

            return new RateLimitRouteWrapper(
                rateLimiter: $rateLimiter,
                pathsConfiguration: App::$config->rateLimit->api->paths->toArray(),
            );
        });
    }
}
