<?php

namespace App\Http\Middleware;

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

class EnsureUserHasRole
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, string $role): Response
    {
        $user = $request->user();

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

        if ($user->role !== $role) {
            // Better UX: if a user hits a panel that is not their role (e.g. browser back),
            // redirect to their correct dashboard instead of showing a 403 page.
            if ($request->expectsJson()) {
                abort(403);
            }
            return redirect()->route('dashboard');
        }

        return $next($request);
    }
}
