<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasPermission
{
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        $user = $request->user();

        if (! $user) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthenticated.',
            ], 401);
        }

        $user->loadMissing('roles.permissions');

        $isAdmin = $user->roles->contains('name', 'admin');

        if (! $isAdmin && ! $user->hasPermission($permission)) {
            return response()->json([
                'success' => false,
                'message' => 'شما دسترسی لازم برای انجام این عملیات را ندارید',
            ], 403);
        }

        return $next($request);
    }
}
