<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class LoginLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'email',
        'ip_address',
        'user_agent',
        'status',
        'failure_reason',
        'user_id',
        'attempted_at'
    ];

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

    /**
     * Relacionamento com o usuário
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope para logs de sucesso
     */
    public function scopeSuccessful($query)
    {
        return $query->where('status', 'success');
    }

    /**
     * Scope para logs de falha
     */
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    /**
     * Scope para logs bloqueados
     */
    public function scopeBlocked($query)
    {
        return $query->where('status', 'blocked');
    }

    /**
     * Scope para logs de um IP específico
     */
    public function scopeFromIp($query, $ip)
    {
        return $query->where('ip_address', $ip);
    }

    /**
     * Scope para logs de um e-mail específico
     */
    public function scopeFromEmail($query, $email)
    {
        return $query->where('email', $email);
    }

    /**
     * Scope para logs de uma data específica
     */
    public function scopeFromDate($query, $date)
    {
        return $query->whereDate('attempted_at', $date);
    }

    /**
     * Scope para logs das últimas X horas
     */
    public function scopeLastHours($query, $hours)
    {
        return $query->where('attempted_at', '>=', now()->subHours($hours));
    }

    /**
     * Verifica se um IP está bloqueado (muitas tentativas falhadas)
     */
    public static function isIpBlocked($ip, $maxAttempts = 5, $timeWindow = 60): bool
    {
        $failedAttempts = self::fromIp($ip)
            ->failed()
            ->lastHours($timeWindow / 60)
            ->count();

        return $failedAttempts >= $maxAttempts;
    }

    /**
     * Verifica se um e-mail está bloqueado (muitas tentativas falhadas)
     */
    public static function isEmailBlocked($email, $maxAttempts = 3, $timeWindow = 60): bool
    {
        $failedAttempts = self::fromEmail($email)
            ->failed()
            ->lastHours($timeWindow / 60)
            ->count();

        return $failedAttempts >= $maxAttempts;
    }

    /**
     * Registra uma tentativa de login
     */
    public static function logAttempt($email, $status, $user = null, $failureReason = null): self
    {
        return self::create([
            'email' => $email,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'status' => $status,
            'failure_reason' => $failureReason,
            'user_id' => $user?->id,
            'attempted_at' => now(),
        ]);
    }
}
