<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

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

    public static function isBlocked(string $ip): bool
    {
        $windowMinutes = 15;
        $maxAttempts   = 5;

        $recentFailures = self::where('ip_address', $ip)
            ->where('successful', false)
            ->where('attempted_at', '>=', now()->subMinutes($windowMinutes))
            ->count();

        return $recentFailures >= $maxAttempts;
    }

    public static function record(string $ip, ?string $email, bool $successful): void
    {
        self::create([
            'ip_address'   => $ip,
            'email'        => $email,
            'successful'   => $successful,
            'attempted_at' => now(),
        ]);
    }
}
