<?php

namespace App\Http\Middleware;

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

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

        if (! $user) {
            return redirect()->route('login');
        }

        if (! $user->hasPermission($permissionSlug)) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Unauthorized access. Required permission: '.$permissionSlug], 403);
            }

            return response()->view('errors.403', [
                'permission' => $permissionSlug,
            ], 403);
        }

        return $next($request);
    }
}
