<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Device extends Model
{
    protected $fillable = [
        'name',
        'goal',
        'weather',
        'quote',
        'brightness',
        'animation',
        'refresh',
        'current_ip',
        'wifi_strength',
        'firmware_version',
        'last_seen',
    ];

    protected $casts = [
        'brightness'  => 'integer',
        'refresh'     => 'integer',
        'wifi_strength' => 'integer',
        'last_seen'   => 'datetime',
    ];

    /**
     * Always work with the single device record.
     */
    public static function sole(): static
    {
        return static::firstOrCreate(
            ['id' => 1],
            [
                'name'             => 'ESP32 Device',
                'goal'             => 'Stay productive',
                'weather'          => '25°C',
                'quote'            => 'Keep Learning',
                'brightness'       => 80,
                'animation'        => 'happy',
                'refresh'          => 30,
                'firmware_version' => 'v1.0.0',
            ]
        );
    }

    /**
     * Return a human-friendly "last seen" string.
     */
    public function getLastSeenHumanAttribute(): string
    {
        return $this->last_seen
            ? $this->last_seen->diffForHumans()
            : 'Never';
    }

    /**
     * Wifi strength as a percentage (0-100 from dBm range -100 to -30).
     */
    public function getWifiPercentAttribute(): ?int
    {
        if ($this->wifi_strength === null) {
            return null;
        }
        $clamped = max(-100, min(-30, $this->wifi_strength));
        return (int) round(($clamped + 100) / 70 * 100);
    }
}
