<?php

declare(strict_types=1);

namespace App\Core;

/** File-based sliding-window rate limiter (no external services on shared hosting). */
final class RateLimiter
{
    public static function check(string $key, int $max, int $windowSeconds): bool
    {
        $dir = dirname(__DIR__, 2) . '/storage/ratelimit';
        if (!is_dir($dir)) {
            mkdir($dir, 0775, true);
        }
        $file = $dir . '/' . sha1($key) . '.json';
        $now = time();

        $hits = [];
        if (file_exists($file)) {
            $hits = json_decode((string) file_get_contents($file), true) ?: [];
        }
        $hits = array_values(array_filter($hits, fn($t) => $t > $now - $windowSeconds));

        if (count($hits) >= $max) {
            return false;
        }
        $hits[] = $now;
        file_put_contents($file, json_encode($hits), LOCK_EX);
        return true;
    }
}
