<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Device extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_ACTIVE = 'active';

    public const STATUS_OFFLINE = 'offline';

    public const STATUS_DISABLED = 'disabled';

    public const MODE_BROWSER_WEDGE = 'browser_wedge';

    public const MODE_AGENT = 'agent';

    public const MODE_WEB_BLUETOOTH = 'web_bluetooth';

    public const MODE_MANUAL = 'manual';

    protected $table = 'care_devices';

    protected $fillable = [
        'owner_ref', 'organization_id', 'branch_id', 'name', 'type',
        'status', 'connection_mode', 'device_token_hash', 'last_seen_at', 'metadata',
    ];

    protected $hidden = [
        'device_token_hash',
    ];

    protected function casts(): array
    {
        return [
            'metadata' => 'array',
            'last_seen_at' => 'datetime',
        ];
    }

    public function organization(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

    public function vitalSigns(): HasMany
    {
        return $this->hasMany(VitalSign::class, 'device_id');
    }

    public function isOnline(int $staleMinutes = 10): bool
    {
        return $this->status === self::STATUS_ACTIVE
            && $this->last_seen_at
            && $this->last_seen_at->gte(now()->subMinutes($staleMinutes));
    }

    public function requiresAgent(): bool
    {
        return $this->connection_mode === self::MODE_AGENT
            || in_array($this->type, config('care.device_agent_types', []), true);
    }

    public function hasToken(): bool
    {
        return filled($this->device_token_hash);
    }
}
