<?php

namespace Modules\Core\Traits;

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

trait AuditableTrait
{
    protected static function bootAuditableTrait()
    {
        // Do NOT run inside console (e.g., seeding)
        if (app()->runningInConsole()) {
            return;
        }

        static::creating(function ($model) {
            if ($model->isFillable('created_by') && empty($model->created_by)) {
                $model->created_by = Auth::id();
            }

            if ($model->isFillable('updated_by') && empty($model->updated_by)) {
                $model->updated_by = Auth::id();
            }
        });

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

    /**
     * Relationship: Who created this model
     */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Relationship: Who last updated this model
     */
    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Check if the record was created by a specific user
     */
    public function isCreatedBy(int $userId): bool
    {
        return $this->created_by === $userId;
    }

    /**
     * Check if the record was updated by a specific user
     */
    public function isUpdatedBy(int $userId): bool
    {
        return $this->updated_by === $userId;
    }
}
