<?php
declare(strict_types=1);

namespace App\Modules\Auth\Models;

use App\Core\App;

class LoginAttempt
{
    public static function record(string $username, string $ip, string $userAgent, bool $success, ?string $failureReason): void
    {
        $db = App::getInstance()->db();
        $db->insert('login_attempts', [
            'username'       => $username,
            'ip_address'     => $ip,
            'user_agent'     => mb_substr($userAgent, 0, 500),
            'success'        => $success ? 1 : 0,
            'failure_reason' => $failureReason,
            'attempted_at'   => date('Y-m-d H:i:s'),
        ]);
    }

    public static function recentFailedCount(string $username, int $minutesBack = 30): int
    {
        $db = App::getInstance()->db();
        $since = date('Y-m-d H:i:s', time() - ($minutesBack * 60));
        $result = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM login_attempts WHERE username = ? AND success = 0 AND attempted_at >= ?",
            [$username, $since]
        );
        return (int) ($result['cnt'] ?? 0);
    }
}