<?php

declare(strict_types=1);

namespace App\Core;

final class Security
{
    public static function csrfToken(): string
    {
        if (empty($_SESSION['_csrf'])) {
            $_SESSION['_csrf'] = bin2hex(random_bytes(32));
        }

        return (string) $_SESSION['_csrf'];
    }

    public static function validateCsrf(?string $token): bool
    {
        return is_string($token)
            && isset($_SESSION['_csrf'])
            && hash_equals((string) $_SESSION['_csrf'], $token);
    }

    public static function rateLimit(string $key, int $maxAttempts, int $windowSeconds): bool
    {
        $now = time();
        $_SESSION['_rate_limits'][$key] ??= [];
        $_SESSION['_rate_limits'][$key] = array_filter(
            $_SESSION['_rate_limits'][$key],
            static fn (int $timestamp): bool => $timestamp > $now - $windowSeconds
        );

        if (count($_SESSION['_rate_limits'][$key]) >= $maxAttempts) {
            return false;
        }

        $_SESSION['_rate_limits'][$key][] = $now;

        return true;
    }

    public static function cleanText(string $value, int $maxLength = 4000): string
    {
        $value = trim(strip_tags($value));
        $value = preg_replace('/\s+/u', ' ', $value) ?? $value;

        return \u_substr($value, 0, $maxLength);
    }
}
