<?php

namespace App\Http\Middleware;

use App\Support\Impersonation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BlockReadOnlyImpersonationWrites
{
    /**
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (! Impersonation::isActive($request) || ! Impersonation::isReadOnly($request)) {
            return $next($request);
        }

        if (in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
            return $next($request);
        }

        if ($request->routeIs('impersonation.stop')) {
            return $next($request);
        }

        $message = 'Modo lectura: no puede realizar cambios mientras impersona a este usuario.';

        if ($request->expectsJson() && ! $request->header('X-Inertia')) {
            abort(Response::HTTP_FORBIDDEN, $message);
        }

        return redirect()
            ->back()
            ->with('error', $message);
    }
}
