<?php

namespace App\Traits;

use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;

trait HasUserstamps
{
    public static function bootHasUserstamps(): void
    {
        // Userstamps are tenant-user FKs (→ users). Resolve from the web guard
        // specifically: in landlord/central context the default guard is
        // `central`, whose ids must never be written here (and console has none).
        static::creating(function ($model): void {
            if ($id = Auth::guard('web')->id()) {
                $model->created_by ??= $id;
                $model->updated_by = $id;
            }
        });

        static::updating(function ($model): void {
            if ($id = Auth::guard('web')->id()) {
                $model->updated_by = $id;
            }
        });
    }

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

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