<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Automation extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'type',
        'name',
        'active',
        'config',
        'last_run_at',
    ];

    protected $casts = [
        'active'      => 'boolean',
        'config'      => 'array',
        'last_run_at' => 'datetime',
    ];

    protected static function boot(): void
    {
        parent::boot();
        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /** Alias für config — für konsistente Lesbarkeit mit der API-Antwort. */
    public function getSettingsAttribute(): array
    {
        return $this->config ?? [];
    }

    public function setSettingsAttribute(array $value): void
    {
        $this->config = $value;
    }

    /** Gibt einen config-Wert zurück, mit Fallback auf den globalen Default. */
    public function cfg(string $key, mixed $default = null): mixed
    {
        return $this->config[$key] ?? $default;
    }
}
