<?php

namespace Modules\Auth\Models;

use CodeIgniter\Model;

class LoginAttemptModel extends Model
{
    protected $table         = 'login_attempts';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false; // created_at set manually below

    protected $allowedFields = [
        'user_id', 'identifier', 'ip_address', 'user_agent',
        'was_successful', 'failure_reason', 'created_at',
    ];

    public function record(array $data): void
    {
        $data['created_at'] = date('Y-m-d H:i:s');
        $this->insert($data);
    }

    /**
     * Count failed attempts for a given identifier and/or IP within the
     * configured rolling window.
     */
    public function recentFailedCount(string $identifier, string $ip, int $windowMinutes): int
    {
        $since = date('Y-m-d H:i:s', time() - ($windowMinutes * 60));

        return $this->where('was_successful', 0)
            ->where('created_at >=', $since)
            ->groupStart()
                ->where('identifier', $identifier)
                ->orWhere('ip_address', $ip)
            ->groupEnd()
            ->countAllResults();
    }

    public function historyForUser(int $userId, int $limit = 25): array
    {
        return $this->where('user_id', $userId)
            ->orderBy('created_at', 'DESC')
            ->findAll($limit);
    }
}
