<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class LoginAttempt extends Model
{
    protected $fillable = [
        'email',
        'ip_address',
        'successful',
        'user_agent',
    ];

    protected $casts = [
        'successful' => 'boolean',
    ];

    // Check if IP is blocked due to too many failed attempts
    public static function isIpBlocked(string $ip, int $maxAttempts = 5, int $minutes = 15): bool
    {
        $attempts = self::where('ip_address', $ip)
            ->where('successful', false)
            ->where('created_at', '>=', now()->subMinutes($minutes))
            ->count();

        return $attempts >= $maxAttempts;
    }

    // Record a login attempt
    public static function record(?string $email, string $ip, bool $successful, ?string $userAgent = null): void
    {
        self::create([
            'email' => $email,
            'ip_address' => $ip,
            'successful' => $successful,
            'user_agent' => $userAgent,
        ]);
    }
}
