<?php

namespace App\Traits;

use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 自动记录创建者/更新者
 */
trait HasCreator
{
    public static function bootHasCreator(): void
    {
        static::creating(function ($model) {
            if (auth()->check()) {
                if ($model->isFillable('created_by') || in_array('created_by', $model->getFillable())) {
                    $model->created_by = $model->created_by ?? auth()->id();
                }
            }
        });

        static::updating(function ($model) {
            if (auth()->check()) {
                if ($model->isFillable('updated_by') || in_array('updated_by', $model->getFillable())) {
                    $model->updated_by = auth()->id();
                }
            }
        });
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }
}
