<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Config\Database;
use App\Core\Response;
use App\Core\MiddlewareInterface;

/**
 * API Throttling: 100 req/min
 */
class RateLimitMiddleware implements MiddlewareInterface
{
    public function handle(): bool
    {
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $userId = $_REQUEST['user']['sub'] ?? $ip;
        $identifier = (string) $userId;

        $db = Database::getInstance();
        $window = date('Y-m-d H:i:s', time() - 60);

        // Delete old limits
        $db->prepare("DELETE FROM rate_limits WHERE window_start < ?")->execute([$window]);

        // Check current
        $stmt = $db->prepare("SELECT SUM(requests) FROM rate_limits WHERE identifier = ? AND window_start >= ?");
        $stmt->execute([$identifier, $window]);
        $count = (int) $stmt->fetchColumn();

        if ($count >= 100) {
            Response::error('Too Many Requests', [], 429);
            return false;
        }

        // Increment
        $stmt = $db->prepare("INSERT INTO rate_limits (identifier, requests) VALUES (?, 1)");
        $stmt->execute([$identifier]);

        return true;
    }
}
