<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth;

/**
 * Simple file-based rate limiter.
 * Stores sliding-window counters in JSON files under sys_get_temp_dir().
 */
final class RateLimiter
{
    private string $prefix;
    private int $maxRequests;
    private int $windowSeconds;

    public function __construct(string $prefix = 'shserv_rl_', int $maxRequests = 10, int $windowSeconds = 60)
    {
        $this->prefix = $prefix;
        $this->maxRequests = $maxRequests;
        $this->windowSeconds = $windowSeconds;
    }

    /**
     * Record a request for the given key and return true if allowed.
     */
    public function check(string $key): bool
    {
        $file = sys_get_temp_dir() . '/' . $this->prefix . md5($key) . '.json';
        $now = time();
        $entries = [];

        if (file_exists($file)) {
            $raw = file_get_contents($file);
            $entries = json_decode($raw, true) ?: [];
            $entries = array_values(array_filter($entries, fn(int $t): bool => $t > $now - $this->windowSeconds));
        }

        if (count($entries) >= $this->maxRequests) {
            return false;
        }

        $entries[] = $now;
        file_put_contents($file, json_encode($entries, JSON_THROW_ON_ERROR), LOCK_EX);
        return true;
    }
}
