<?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\Permission as SpatiePermission;

class Permission extends SpatiePermission
{
    use HasFactory, LogsActivity, SoftDeletes;

    /**
     * Activity log configuration
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('permission-management')
            ->logOnly(['name', 'guard_name', 'is_active'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    /**
     * Ketika permission diupdate
     */
    public function updated(\App\Models\Permission $permission)
    {
        \Illuminate\Support\Facades\Cache::forget("permission_status:{$permission->name}");
    }

    /**
     * Ketika permission didelete (termasuk soft delete)
     */
    public function deleted(\App\Models\Permission $permission)
    {
        \Illuminate\Support\Facades\Cache::forget("permission_status:{$permission->name}");
    }

    /**
     * Fillable attributes
     */
    protected $fillable = [
        'name',
        'guard_name',
        'is_active',
        'created_by',
        'updated_by',
    ];

    /**
     * Casting
     */
    protected $casts = [
        'is_active' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

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

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

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