<?php

namespace App\Observers;

use App\Models\Permission;
use Illuminate\Support\Facades\Auth;

class PermissionObserver
{
    /**
     * Ketika permission sedang dibuat
     */
    public function creating(\App\Models\Permission $permission)
    {
        if (Auth::check()) {
            $permission->created_by = Auth::id();
        }
    }

    /**
     * Ketika permission sedang diupdate
     */
    public function updating(\App\Models\Permission $permission)
    {
        if (Auth::check()) {
            $permission->updated_by = Auth::id();
        }
    }

    /**
     * Ketika permission selesai 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}");
        
        if (Auth::check()) {
            $permission->updated_by = Auth::id();
            $permission->saveQuietly();
        }
    }
}
