<?php
namespace PortalPeople\DisabledPostcodes\Model;

use Magento\Framework\App\CacheInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Phrase;

class ApiRateLimiter
{
    private CacheInterface $cache;

    public function __construct(CacheInterface $cache)
    {
        $this->cache = $cache;
    }

    public function assertAllowed(string $key, int $limit = 60, int $windowSeconds = 60): void
    {
        $bucket = (int)floor(time() / $windowSeconds);
        $cacheKey = 'pp_disabled_postcodes_rl_' . md5($key . '|' . $bucket);
        $current = (int)$this->cache->load($cacheKey);

        if ($current >= $limit) {
            throw new LocalizedException(new Phrase('Too many requests. Please try again shortly.'));
        }

        $this->cache->save((string)($current + 1), $cacheKey, [], $windowSeconds);
    }
}
