<?php

namespace App\Models;

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

class BioTimeDevice extends Model
{
    use HasFactory;

    protected $fillable = [
        'sn',
        'alias',
        'ip_address',
        'device_model',
        'area_id',
        'last_activity',
        'status',
        'is_active',
    ];

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

    public function isOnline(int $minutes = 5): bool
    {
        return (bool) ($this->last_activity?->gt(now()->subMinutes($minutes)));
    }

    public function getDisplayStatusAttribute(): string
    {
        return $this->isOnline() ? 'online' : 'offline';
    }

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

    public function commands(): HasMany
    {
        return $this->hasMany(DeviceCommand::class, 'device_sn', 'sn');
    }
}
