<?php

namespace App\Http\Middleware;

use App\Domain\Shared\Context\BranchContext;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Keep a user who is viewing every branch out of branch-scoped pages.
 *
 * Hiding sidebar items is cosmetic — the URLs stay reachable, and a bookmark
 * would show un-scoped operational data. This closes that.
 *
 * It runs on the whole web group with an allow-list rather than being attached
 * to ~175 individual routes: routes/web.php is one flat auth group, so
 * per-route application would mean restructuring the file for an additive
 * feature. The allow-list lives in config/branch_lock.php, shared with the
 * sidebar so the two cannot drift.
 */
class RequireBranchSelection
{
    public function __construct(private BranchContext $branch)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()) {
            return $next($request);
        }

        $redirectRoute = $this->branch->redirectRouteName();

        // Loop guard: the destination must always be reachable, even if someone
        // removes it from the allow-list by accident.
        if ($request->routeIs($redirectRoute)) {
            return $next($request);
        }

        // Not viewing all branches — single-branch users and anyone who has
        // picked a branch pass straight through, unchanged.
        if (! $this->branch->isLocked()) {
            return $next($request);
        }

        if ($this->branch->routeIsUnlocked($request->route()?->getName())) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'message' => __('اختر فرعاً أولاً للوصول إلى هذه البيانات.'),
            ], 403);
        }

        return redirect()
            ->route($redirectRoute)
            ->with('error', __('اختر فرعاً من القائمة العلوية للوصول إلى هذه الصفحة.'));
    }
}
