<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    use HasFactory, LogsActivity, SoftDeletes;

    /**
     * Activity log configuration for Role
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('role-management') // module log category
            ->logOnly(['name', 'guard_name', 'is_active']) // fields to monitor
            ->logOnlyDirty()                               // only log if changed
            ->dontSubmitEmptyLogs();                       // skip if no changes
    }

    protected $fillable = [
        'name',
        'guard_name',
        'is_active',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    /**
     * Boot model to automatically set created_by & updated_by
     */
    protected static function boot()
    {
        parent::boot();

        // Automatically set created_by
        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
            }
        });

        // Automatically set updated_by (including soft deletes)
        static::updating(function ($model) {
            if (Auth::check()) {
                $model->updated_by = Auth::id();
            }
        });

        static::deleting(function ($model) {
            if (Auth::check()) {
                $model->updated_by = Auth::id();
                $model->saveQuietly(); // save without triggering infinite update log
            }
        });
    }

    /**
     * Audit Trail Relationships
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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