<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class SopTemplate extends Model
{
    use HasFactory, SoftDeletes, LogsActivity;

    /**
     * 可批量赋值的属性
     *
     * @var array<string>
     */
    protected $fillable = [
        'name',
        'description',
        'category',
        'tags',
        'version',
        'status',
        'applicable_departments',
        'applicable_positions',
        'published_at',
        'created_by',
    ];

    /**
     * 属性类型转换
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'tags' => 'array',
            'applicable_departments' => 'array',
            'applicable_positions' => 'array',
            'published_at' => 'datetime',
        ];
    }

    /**
     * 获取模板的步骤列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function steps()
    {
        return $this->hasMany(SopStep::class)->orderBy('sort_order');
    }

    /**
     * 获取模板的版本历史
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function versions()
    {
        return $this->hasMany(SopTemplateVersion::class);
    }

    /**
     * 获取模板的创建者
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 配置活动日志选项
     *
     * @return \Spatie\Activitylog\LogOptions
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['name', 'description', 'category', 'status', 'version'])
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "SOP模板已{$eventName}");
    }
}
