<?php

namespace App\Models;

use App\Models\BaseModel;

class IpAttempt extends BaseModel
{
    protected $table = 'ip_attempts';

    // ✅ legacy: useTimestamps = true (created_at/updated_at)
    public $timestamps = true;

    protected $fillable = [
        'ip_address',
        'attempts',
        'last_attempt_at',
        'semester',
        'school_year',
        'blocked_until',
    ];

    protected $casts = [
        'attempts'        => 'integer',
        'last_attempt_at' => 'datetime',
        'blocked_until'   => 'datetime',
    ];

    /**
     * Equivalent of legacy getAttemptByIp()
     */
    public static function getAttemptByIp(string $ip): ?self
    {
        return static::query()
            ->where('ip_address', $ip)
            ->first();
    }

    /**
     * Equivalent of legacy updateIpAttempt()
     */
    public static function updateIpAttempt(string $ip, array $data): bool
    {
        return static::query()
            ->where('ip_address', $ip)
            ->update($data) >= 0;
    }

    /**
     * Equivalent of legacy insertIpAttempt()
     * Returns inserted id.
     */
    public static function insertIpAttempt(array $data): int
    {
        $row = static::query()->create($data);
        return (int) $row->id;
    }
}