<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AppSetting extends Model
{
    protected $fillable = [
        'config_version', 'match_threshold', 'liveness_enabled', 'liveness_threshold',
        'debounce_minutes', 'direction_area_ratio', 'min_direction_confidence',
        'sync_interval_s', 'heartbeat_interval_s', 'snapshot_upload',
        'shift_start', 'shift_end',
    ];

    protected function casts(): array
    {
        return [
            'liveness_enabled' => 'boolean',
            'snapshot_upload' => 'boolean',
            'match_threshold' => 'float',
            'liveness_threshold' => 'float',
            'direction_area_ratio' => 'float',
            'min_direction_confidence' => 'float',
        ];
    }

    /** There is a single settings row (id=1); create it with defaults if missing. */
    public static function current(): self
    {
        // Explicit defaults here (not just relying on migration column defaults) so the
        // in-memory model is fully populated immediately after first creation — Eloquent's
        // create() does not re-fetch server-applied column defaults after INSERT.
        return static::query()->firstOrCreate(['id' => 1], [
            'config_version' => 1,
            'match_threshold' => 0.40,
            'liveness_enabled' => true,
            'liveness_threshold' => 0.5,
            'debounce_minutes' => 3,
            'direction_area_ratio' => 1.25,
            'min_direction_confidence' => 0.6,
            'sync_interval_s' => 30,
            'heartbeat_interval_s' => 60,
            'snapshot_upload' => true,
            'shift_start' => '09:30',
            'shift_end' => '18:00',
        ]);
    }

    public function toConfigArray(): array
    {
        return [
            'config_version' => $this->config_version,
            'match_threshold' => $this->match_threshold,
            'liveness_enabled' => $this->liveness_enabled,
            'liveness_threshold' => $this->liveness_threshold,
            'debounce_minutes' => $this->debounce_minutes,
            'direction_area_ratio' => $this->direction_area_ratio,
            'min_direction_confidence' => $this->min_direction_confidence,
            'sync_interval_s' => $this->sync_interval_s,
            'heartbeat_interval_s' => $this->heartbeat_interval_s,
            'snapshot_upload' => $this->snapshot_upload,
            'shift_start' => $this->shift_start,
            'shift_end' => $this->shift_end,
        ];
    }
}
