<?php

declare(strict_types=1);

namespace App\Core;

/**
 * Limitation simple des tentatives de connexion (par session).
 */
final class LoginThrottle
{
    private const KEY = '_login_throttle';

    public function __construct(
        private readonly int $maxAttempts = 5,
        private readonly int $decaySeconds = 300,
    ) {
    }

    public function tooManyAttempts(): bool
    {
        $data = $_SESSION[self::KEY] ?? null;
        if (!is_array($data)) {
            return false;
        }

        return ($data['attempts'] ?? 0) >= $this->maxAttempts
            && time() < ($data['until'] ?? 0);
    }

    public function hit(): void
    {
        $data             = $_SESSION[self::KEY] ?? ['attempts' => 0, 'until' => 0];
        $data['attempts'] = (int) ($data['attempts'] ?? 0) + 1;

        if ($data['attempts'] >= $this->maxAttempts) {
            $data['until'] = time() + $this->decaySeconds;
        }

        $_SESSION[self::KEY] = $data;
    }

    public function clear(): void
    {
        unset($_SESSION[self::KEY]);
    }

    public function secondsRemaining(): int
    {
        $until = $_SESSION[self::KEY]['until'] ?? 0;
        return max(0, (int) $until - time());
    }
}
