<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Spatie\Permission\Models\Permission;

class CheckActivePermission
{
    public function handle(Request $request, Closure $next, $permission)
    {
        $cacheKey = "permission_status:{$permission}";

        $isActive = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($permission) {
            $permissionModel = Permission::where('name', $permission)->first();

            return $permissionModel && $permissionModel->is_active;
        });

        // If permission not found OR inactive -> deny access
        if (! $isActive) {
            abort(403, 'This permission is inactive or not available.');
        }

        // Continue request (permission is active)
        return $next($request);
    }
}
