<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;

class DeviceLog extends Model
{
    protected $fillable = [
        'license_id',
        'device_id',
        'device_name',
        'device_type',
        'os',
        'browser',
        'ip_address',
        'country',
        'city',
        'user_agent',
        'action',
        'is_active',
        'last_seen',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'last_seen' => 'datetime',
    ];

    public function license(): BelongsTo
    {
        return $this->belongsTo(License::class);
    }

    public function markActive(): void
    {
        $this->update([
            'is_active' => true,
            'last_seen' => Carbon::now(),
        ]);
    }

    public function markInactive(): void
    {
        $this->update(['is_active' => false]);
    }

    public function updateHeartbeat(): void
    {
        $this->update(['last_seen' => Carbon::now()]);
    }

    public function isStale(int $minutes = 30): bool
    {
        return $this->last_seen && Carbon::now()->greaterThan($this->last_seen->addMinutes($minutes));
    }
}