<?php

namespace App\Http\Middleware;

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

class EnsureCanEdit
{
    protected array $readOnlyActions = ['index', 'show'];

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (! $user) {
            return redirect()->route('login');
        }
        if ($user->canEdit()) {
            return $next($request);
        }
        $route = $request->route();
        $action = $route?->getActionName();
        $isReadOnly = $route && in_array($route->getActionMethod(), $this->readOnlyActions, true);

        if ($isReadOnly) {
            return $next($request);
        }

        return redirect()->back()->with('error', 'Vous n\'avez pas les droits pour effectuer cette action.');
    }
}
