<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Database;

final class LoginAttempt
{
    public static function record(string $email, string $ip, bool $ok): void
    {
        Database::instance()->query(
            'INSERT INTO login_attempts (email, ip, succeeded) VALUES (:email, :ip, :ok)',
            ['email' => $email, 'ip' => $ip, 'ok' => $ok ? 1 : 0]
        );
    }

    public static function tooMany(string $email, string $ip, int $max, int $minutes): bool
    {
        $minutes = max(1, $minutes);
        $count = (int) Database::instance()->fetchColumn(
            "SELECT COUNT(*) FROM login_attempts
             WHERE succeeded = 0 AND attempted_at > DATE_SUB(NOW(), INTERVAL {$minutes} MINUTE)
               AND (email = :email OR ip = :ip)",
            ['email' => $email, 'ip' => $ip]
        );
        return $count >= $max;
    }
}
