<?php

namespace App\Modules\Inventory\Support;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;

/**
 * @mixin Model
 */
trait InventoryUserStamp
{
    protected static function bootInventoryUserStamp(): void
    {
        static::creating(function (Model $model): void {
            $uid = self::currentUserId();
            if ($uid === null) {
                return;
            }
            if ($model->getAttribute('created_by') === null) {
                $model->setAttribute('created_by', $uid);
            }
            if ($model->getAttribute('updated_by') === null) {
                $model->setAttribute('updated_by', $uid);
            }
        });

        static::updating(function (Model $model): void {
            $uid = self::currentUserId();
            if ($uid !== null) {
                $model->setAttribute('updated_by', $uid);
            }
        });
    }

    private static function currentUserId(): ?int
    {
        $user = auth()->user();

        return $user instanceof User ? (int) $user->id : null;
    }
}
